@chainingintention/pi-web-cn 1.202606.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +364 -0
  3. package/dist/cli.js +960 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/client/apple-touch-icon.png +0 -0
  6. package/dist/client/assets/CodeViewer-B4nxYc0g.js +4 -0
  7. package/dist/client/assets/TerminalPanel-htr2dU1I.js +122 -0
  8. package/dist/client/assets/index-BjUH4a8R.js +1994 -0
  9. package/dist/client/assets/vendor-editor-core-B4Sq6exx.js +12 -0
  10. package/dist/client/assets/vendor-editor-languages-DznYbTkJ.js +26 -0
  11. package/dist/client/assets/vendor-editor-legacy-B4QLsWF8.js +1 -0
  12. package/dist/client/assets/vendor-terminal-DDGTF8rc.css +1 -0
  13. package/dist/client/assets/vendor-terminal-DjQ08hXu.js +16 -0
  14. package/dist/client/favicon.svg +11 -0
  15. package/dist/client/index.html +60 -0
  16. package/dist/client/manifest.webmanifest +24 -0
  17. package/dist/client/pwa-icon-192.png +0 -0
  18. package/dist/client/pwa-icon-512.png +0 -0
  19. package/dist/config.js +154 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/pi-web-plugins/info/package.json +9 -0
  22. package/dist/pi-web-plugins/info/pi-web-plugin.js +51 -0
  23. package/dist/pi-web-plugins/updates/package.json +9 -0
  24. package/dist/pi-web-plugins/updates/pi-web-plugin.js +181 -0
  25. package/dist/pi-web-plugins/workspace-tasks/config.js +91 -0
  26. package/dist/pi-web-plugins/workspace-tasks/package.json +9 -0
  27. package/dist/pi-web-plugins/workspace-tasks/pi-web-plugin.js +48 -0
  28. package/dist/pi-web-plugins/workspace-tasks/taskRunner.js +12 -0
  29. package/dist/pi-web-plugins/workspace-tasks/tasksPanelElement.js +292 -0
  30. package/dist/pi-web-plugins/workspace-tasks/workspaceTasksClient.js +47 -0
  31. package/dist/piWebVersionReport.js +221 -0
  32. package/dist/piWebVersionReport.js.map +1 -0
  33. package/dist/plugin-api/unstable.d.ts +22 -0
  34. package/dist/plugin-api.d.ts +163 -0
  35. package/dist/server/activity/workspaceActivityRoutes.js +4 -0
  36. package/dist/server/activity/workspaceActivityRoutes.js.map +1 -0
  37. package/dist/server/activity/workspaceActivityService.js +98 -0
  38. package/dist/server/activity/workspaceActivityService.js.map +1 -0
  39. package/dist/server/app.js +115 -0
  40. package/dist/server/app.js.map +1 -0
  41. package/dist/server/configRoutes.js +123 -0
  42. package/dist/server/configRoutes.js.map +1 -0
  43. package/dist/server/diagnostics/nodePtySpawnHelper.js +135 -0
  44. package/dist/server/diagnostics/nodePtySpawnHelper.js.map +1 -0
  45. package/dist/server/git/gitEnv.js +15 -0
  46. package/dist/server/git/gitEnv.js.map +1 -0
  47. package/dist/server/git/gitService.js +119 -0
  48. package/dist/server/git/gitService.js.map +1 -0
  49. package/dist/server/gitRoutes.js +23 -0
  50. package/dist/server/gitRoutes.js.map +1 -0
  51. package/dist/server/index.js +7 -0
  52. package/dist/server/index.js.map +1 -0
  53. package/dist/server/machines/machineClient.js +134 -0
  54. package/dist/server/machines/machineClient.js.map +1 -0
  55. package/dist/server/machines/machineProxyRoutes.js +92 -0
  56. package/dist/server/machines/machineProxyRoutes.js.map +1 -0
  57. package/dist/server/machines/machineRoutes.js +50 -0
  58. package/dist/server/machines/machineRoutes.js.map +1 -0
  59. package/dist/server/machines/machineService.js +168 -0
  60. package/dist/server/machines/machineService.js.map +1 -0
  61. package/dist/server/machines/machineStore.js +128 -0
  62. package/dist/server/machines/machineStore.js.map +1 -0
  63. package/dist/server/piWebPluginService.js +235 -0
  64. package/dist/server/piWebPluginService.js.map +1 -0
  65. package/dist/server/piWebStatus.js +462 -0
  66. package/dist/server/piWebStatus.js.map +1 -0
  67. package/dist/server/projects/directorySuggestions.js +37 -0
  68. package/dist/server/projects/directorySuggestions.js.map +1 -0
  69. package/dist/server/projects/projectService.js +31 -0
  70. package/dist/server/projects/projectService.js.map +1 -0
  71. package/dist/server/realtime/sessionEventHub.js +39 -0
  72. package/dist/server/realtime/sessionEventHub.js.map +1 -0
  73. package/dist/server/sessiond/sessionProxyRoutes.js +60 -0
  74. package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -0
  75. package/dist/server/sessiond.js +61 -0
  76. package/dist/server/sessiond.js.map +1 -0
  77. package/dist/server/sessions/authProviderOptions.js +56 -0
  78. package/dist/server/sessions/authProviderOptions.js.map +1 -0
  79. package/dist/server/sessions/authRoutes.js +59 -0
  80. package/dist/server/sessions/authRoutes.js.map +1 -0
  81. package/dist/server/sessions/authService.js +74 -0
  82. package/dist/server/sessions/authService.js.map +1 -0
  83. package/dist/server/sessions/builtinCommands.js +27 -0
  84. package/dist/server/sessions/builtinCommands.js.map +1 -0
  85. package/dist/server/sessions/editPreview.js +196 -0
  86. package/dist/server/sessions/editPreview.js.map +1 -0
  87. package/dist/server/sessions/messagePaging.js +43 -0
  88. package/dist/server/sessions/messagePaging.js.map +1 -0
  89. package/dist/server/sessions/oauthLoginFlowService.js +219 -0
  90. package/dist/server/sessions/oauthLoginFlowService.js.map +1 -0
  91. package/dist/server/sessions/piSessionService.js +1054 -0
  92. package/dist/server/sessions/piSessionService.js.map +1 -0
  93. package/dist/server/sessions/sessionArchiveStore.js +216 -0
  94. package/dist/server/sessions/sessionArchiveStore.js.map +1 -0
  95. package/dist/server/sessions/sessionArchiveTree.js +35 -0
  96. package/dist/server/sessions/sessionArchiveTree.js.map +1 -0
  97. package/dist/server/sessions/sessionCommandService.js +234 -0
  98. package/dist/server/sessions/sessionCommandService.js.map +1 -0
  99. package/dist/server/sessions/sessionNameGenerator.js +68 -0
  100. package/dist/server/sessions/sessionNameGenerator.js.map +1 -0
  101. package/dist/server/sessions/sessionRoutes.js +184 -0
  102. package/dist/server/sessions/sessionRoutes.js.map +1 -0
  103. package/dist/server/sessions/sessionRuntimeStore.js +2 -0
  104. package/dist/server/sessions/sessionRuntimeStore.js.map +1 -0
  105. package/dist/server/storage/projectStore.js +88 -0
  106. package/dist/server/storage/projectStore.js.map +1 -0
  107. package/dist/server/terminalProxyRoutes.js +130 -0
  108. package/dist/server/terminalProxyRoutes.js.map +1 -0
  109. package/dist/server/terminals/terminalRoutes.js +138 -0
  110. package/dist/server/terminals/terminalRoutes.js.map +1 -0
  111. package/dist/server/terminals/terminalService.js +293 -0
  112. package/dist/server/terminals/terminalService.js.map +1 -0
  113. package/dist/server/terminals/terminalSize.js +17 -0
  114. package/dist/server/terminals/terminalSize.js.map +1 -0
  115. package/dist/server/types.js +2 -0
  116. package/dist/server/types.js.map +1 -0
  117. package/dist/server/webSocketBridge.js +32 -0
  118. package/dist/server/webSocketBridge.js.map +1 -0
  119. package/dist/server/workspaceExplorerRoutes.js +42 -0
  120. package/dist/server/workspaceExplorerRoutes.js.map +1 -0
  121. package/dist/server/workspaces/fileContentService.js +70 -0
  122. package/dist/server/workspaces/fileContentService.js.map +1 -0
  123. package/dist/server/workspaces/fileSuggestions.js +148 -0
  124. package/dist/server/workspaces/fileSuggestions.js.map +1 -0
  125. package/dist/server/workspaces/fileTreeService.js +26 -0
  126. package/dist/server/workspaces/fileTreeService.js.map +1 -0
  127. package/dist/server/workspaces/gitWorktreeDiscovery.js +34 -0
  128. package/dist/server/workspaces/gitWorktreeDiscovery.js.map +1 -0
  129. package/dist/server/workspaces/imagePreviewService.js +40 -0
  130. package/dist/server/workspaces/imagePreviewService.js.map +1 -0
  131. package/dist/server/workspaces/pathSafety.js +45 -0
  132. package/dist/server/workspaces/pathSafety.js.map +1 -0
  133. package/dist/server/workspaces/workspaceContext.js +8 -0
  134. package/dist/server/workspaces/workspaceContext.js.map +1 -0
  135. package/dist/server/workspaces/workspaceService.js +39 -0
  136. package/dist/server/workspaces/workspaceService.js.map +1 -0
  137. package/dist/sessiond/config.js +9 -0
  138. package/dist/sessiond/config.js.map +1 -0
  139. package/dist/sessiond/sessionDaemonClient.js +65 -0
  140. package/dist/sessiond/sessionDaemonClient.js.map +1 -0
  141. package/dist/shared/activity.js +26 -0
  142. package/dist/shared/activity.js.map +1 -0
  143. package/dist/shared/apiTypes.d.ts +464 -0
  144. package/dist/shared/apiTypes.js +2 -0
  145. package/dist/shared/apiTypes.js.map +1 -0
  146. package/dist/shared/federatedRoutes.js +57 -0
  147. package/dist/shared/federatedRoutes.js.map +1 -0
  148. package/dist/shared/piWebStatusParsing.js +62 -0
  149. package/dist/shared/piWebStatusParsing.js.map +1 -0
  150. package/dist/shared/pluginIds.js +5 -0
  151. package/dist/shared/pluginIds.js.map +1 -0
  152. package/dist/shared/workspaceFiles.js +3 -0
  153. package/dist/shared/workspaceFiles.js.map +1 -0
  154. package/docs/assets/favicon.svg +11 -0
  155. package/docs/assets/pi-web-banner.png +0 -0
  156. package/docs/assets/pi-web-demo.gif +0 -0
  157. package/docs/assets/pi-web-demo.webm +0 -0
  158. package/docs/plugins.md +762 -0
  159. package/extensions/pi-web.ts +133 -0
  160. package/install.sh +5 -0
  161. package/package.json +127 -0
  162. package/plugin-api/unstable.d.ts +1 -0
  163. package/plugin-api.d.ts +1 -0
@@ -0,0 +1,1994 @@
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?`不加入上下文
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)?"":`
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(`
10
+
11
+ `)&&(t.output===void 0||t.output==="")&&r.push("(no output)"),t.isError===!0&&r.push(t.output??"Bash 命令失败"),t.exitCode!=null&&r.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&r.push("cancelled"),t.truncated===!0&&r.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&r.push(`完整输出:${t.fullOutputPath}`),r.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
+
13
+ ${r.join(`
14
+ `)}`}]}]}function fc(e){const t=e.lastIndexOf(`
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(`
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`
21
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
22
+ <circle cx="6" cy="7" r="1.5"></circle>
23
+ <path d="M10 7h8"></path>
24
+ <circle cx="6" cy="12" r="1.5"></circle>
25
+ <path d="M10 12h8"></path>
26
+ <circle cx="6" cy="17" r="1.5"></circle>
27
+ <path d="M10 17h8"></path>
28
+ </svg>
29
+ `;case"chat":return Xe`
30
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
31
+ <path d="M7 5h10a3 3 0 0 1 3 3v5a3 3 0 0 1-3 3h-6l-5 4v-4H7a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3Z"></path>
32
+ <path d="M8 9h8"></path>
33
+ <path d="M8 13h5"></path>
34
+ </svg>
35
+ `;case"files":return Xe`
36
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
37
+ <path d="M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"></path>
38
+ </svg>
39
+ `;case"git":return Xe`
40
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
41
+ <circle cx="6" cy="6" r="2"></circle>
42
+ <circle cx="18" cy="6" r="2"></circle>
43
+ <circle cx="12" cy="18" r="2"></circle>
44
+ <path d="M8 6h6"></path>
45
+ <path d="M6 8v2a6 6 0 0 0 6 6"></path>
46
+ <path d="M18 8v2a6 6 0 0 1-6 6"></path>
47
+ </svg>
48
+ `;case"terminal":return Xe`
49
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
50
+ <rect x="3" y="5" width="18" height="14" rx="2"></rect>
51
+ <path d="m7 10 3 3-3 3"></path>
52
+ <path d="M12 16h5"></path>
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`
55
+ <section class="toolbar">
56
+ <strong>文件</strong>
57
+ ${e.fileTreeStale?l`<span class="stale">过期</span>`:null}
58
+ <button @click=${e.onRefreshFiles}>刷新</button>
59
+ </section>
60
+ <section class="split">
61
+ <div class="list tree">
62
+ ${e.fileTree.length===0?l`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(t=>No(e,t,0))}
63
+ </div>
64
+ <div class="viewer">
65
+ ${Kd(e)}
66
+ </div>
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)}}>
70
+ <span>${t.type==="directory"?r?"▾":"▸":"·"}</span>
71
+ <span>${t.name}</span>
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`
75
+ <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"文本"}${t.truncated?" · 已截断":""}</small></div>
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`
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`
81
+ <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
82
+ <div class="image-preview">
83
+ <img src=${s} alt=${t.path} decoding="async" />
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`
86
+ <section class="toolbar">
87
+ <strong>Git</strong>
88
+ ${e.gitStale?l`<span class="stale">过期</span>`:null}
89
+ <button @click=${e.onRefreshGit}>刷新</button>
90
+ </section>
91
+ <section class="split">
92
+ <div class="list">
93
+ ${t===void 0?l`<p class="muted">尚未加载状态。</p>`:t.isGitRepo?l`
94
+ <p class="summary">${ep(t)}</p>
95
+ ${t.files.length===0?l`<p class="muted">没有变更。</p>`:t.files.map(i=>l`
96
+ <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
97
+ <span>${tp(i.index,i.workingTree)}</span>
98
+ <span>${i.path}</span>
99
+ </button>
100
+ `)}
101
+ `:l`<p class="muted">不是 Git 仓库。</p>`}
102
+ </div>
103
+ <div class="viewer">
104
+ ${Zd(e)}
105
+ </div>
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`
108
+ <div class=${s.length===1?"diffs single":"diffs"}>
109
+ ${s.map(r=>Xd(r))}
110
+ </div>
111
+ `}function Xd(e){return Bo(),l`
112
+ <section class="diff-section">
113
+ <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
114
+ <code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
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`
117
+ /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
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
+ :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
120
+ @media (display-mode: standalone), (display-mode: fullscreen), (display-mode: minimal-ui) {
121
+ :host { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
122
+ }
123
+ .shell { --navigation-panel-width: 340px; --workspace-panel-width: minmax(360px, 42vw); display: grid; grid-template-columns: var(--navigation-panel-width) 1px minmax(420px, 1fr) 1px var(--workspace-panel-width); height: 100%; min-height: 0; }
124
+ aside { grid-column: 1; display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
125
+ aside app-navigation-panel { flex: 1 1 auto; min-height: 0; }
126
+ header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
127
+ .header-actions { display: flex; align-items: center; gap: 8px; }
128
+ project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
129
+ session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
130
+ main { grid-column: 3; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
131
+ .context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: none; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
132
+ .context-bar::before, .context-bar::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
133
+ .context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
134
+ .context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
135
+ .context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
136
+ .context-bar-label { display: none; }
137
+ .context-items { flex: 1 1 auto; min-width: 0; display: flex; align-items: stretch; gap: 5px; margin: 0; padding: 0 8px; list-style: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scroll-padding-inline: 8px; scrollbar-width: thin; }
138
+ .context-bar.has-context-actions .context-items { padding-right: 52px; scroll-padding-inline: 8px 52px; }
139
+ .context-item { flex: 0 0 auto; min-width: 0; display: flex; }
140
+ .context-actions { position: absolute; top: 6px; right: 0; bottom: 6px; z-index: 3; display: flex; align-items: center; padding: 0 8px 0 0; pointer-events: none; }
141
+ .context-actions::after { content: ""; position: absolute; top: 0; right: 0; bottom: 0; z-index: 0; width: 26px; background: var(--pi-bg); pointer-events: none; }
142
+ .app-refresh { position: relative; z-index: 1; display: flex; align-items: center; pointer-events: auto; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
143
+ .app-refresh, .app-refresh * { -webkit-user-select: none; user-select: none; }
144
+ .app-refresh-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border-radius: 999px; padding: 0; line-height: 1; touch-action: manipulation; -webkit-touch-callout: none; }
145
+ .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
146
+ .app-refresh-button.refreshing .app-refresh-icon { animation: app-refresh-spin .8s linear infinite; }
147
+ .app-refresh-menu { position: fixed; z-index: 10000; box-sizing: border-box; min-width: min(170px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); overflow-wrap: anywhere; }
148
+ .app-refresh-menu button { display: block; width: 100%; border: 0; background: transparent; color: var(--pi-text); text-align: left; white-space: normal; overflow-wrap: anywhere; }
149
+ .app-refresh-menu button:hover, .app-refresh-menu button:focus { background: var(--pi-selection-bg); }
150
+ .context-chip { flex: 0 0 auto; min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 8px; font: inherit; text-align: left; }
151
+ .context-chip:hover { background: var(--pi-surface-hover); }
152
+ .context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
153
+ .context-chip.empty { border-style: dashed; color: var(--pi-muted); }
154
+ .context-kind { display: none; }
155
+ .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
156
+ app-mobile-main-tabs { display: none; }
157
+ .mobile-tabs-frame { position: relative; display: none; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
158
+ .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; }
159
+ .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
160
+ .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
161
+ .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
162
+ .mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
163
+ .mobile-tabs button { flex: 0 0 auto; white-space: nowrap; }
164
+ .mobile-navigation-tab, .mobile-navigation-panel { display: none; }
165
+ .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
166
+ .tab-badge { display: inline-block; min-width: 14px; margin-left: 4px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
167
+ .navigation-panel-edge, .workspace-panel-edge { min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
168
+ .navigation-panel-edge { grid-column: 2; }
169
+ .workspace-panel-edge { grid-column: 4; }
170
+ .navigation-panel-edge-button, .workspace-panel-edge-button { position: relative; z-index: 1; box-sizing: border-box; display: grid; place-items: center; width: 18px; height: 48px; padding: 0; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-bg); color: var(--pi-muted); opacity: .75; cursor: pointer; }
171
+ .navigation-panel-edge-button:hover, .navigation-panel-edge-button:focus-visible, .workspace-panel-edge-button:hover, .workspace-panel-edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
172
+ .shell.navigation-panel-collapsed .navigation-panel-edge-button { transform: translateX(calc(50% - .5px)); }
173
+ .shell.workspace-panel-collapsed .workspace-panel-edge-button { transform: translateX(calc(-50% + .5px)); }
174
+ .navigation-panel-edge-icon, .workspace-panel-edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
175
+ workspace-panel { grid-column: 5; min-width: 0; min-height: 0; overflow: hidden; }
176
+ @media (min-width: 1181px) {
177
+ .shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
178
+ .shell.navigation-panel-collapsed > aside { display: none; }
179
+ .shell.workspace-panel-collapsed { --workspace-panel-width: 0px; }
180
+ .shell.workspace-panel-collapsed > workspace-panel { display: none; }
181
+ }
182
+ @media (max-width: 1180px) {
183
+ .shell { grid-template-columns: var(--navigation-panel-width) 1px minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
184
+ .shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
185
+ .shell.navigation-panel-collapsed > aside { display: none; }
186
+ aside { grid-row: 1 / 3; }
187
+ .navigation-panel-edge { grid-row: 1 / 3; }
188
+ main { grid-column: 3; grid-row: 1 / 3; }
189
+ app-mobile-main-tabs { display: block; flex: 0 0 auto; min-width: 0; }
190
+ .mobile-tabs-frame { display: flex; }
191
+ .shell.workspace-view main { grid-row: 1; min-height: auto; }
192
+ .shell.workspace-view > workspace-panel { grid-column: 3; grid-row: 2; display: flex; border-left: 0; }
193
+ .shell:not(.workspace-view) > workspace-panel { display: none; }
194
+ .workspace-panel-edge { display: none; }
195
+ main.workspace-view chat-view, main.workspace-view prompt-editor, main.workspace-view status-bar,
196
+ main.workspace-view .empty { display: none; }
197
+ main.workspace-view { overflow: hidden; }
198
+ }
199
+ @media (max-width: 760px) {
200
+ .shell { grid-template-columns: minmax(0, 1fr); }
201
+ aside, .navigation-panel-edge { display: none; }
202
+ main, .shell.workspace-view > workspace-panel { grid-column: 1; }
203
+ .context-bar { display: flex; }
204
+ .mobile-navigation-tab { display: block; }
205
+ main.navigation-view chat-view, main.navigation-view prompt-editor, main.navigation-view status-bar,
206
+ main.navigation-view .empty { display: none; }
207
+ main.navigation-view .mobile-navigation-panel { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
208
+ main.navigation-view .mobile-navigation-panel app-navigation-panel { flex: 1 1 auto; min-height: 0; }
209
+ main.navigation-view .mobile-navigation-panel project-list,
210
+ main.navigation-view .mobile-navigation-panel workspace-list,
211
+ main.navigation-view .mobile-navigation-panel session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
212
+ main.navigation-view .mobile-navigation-panel project-list[collapsed],
213
+ main.navigation-view .mobile-navigation-panel workspace-list[collapsed],
214
+ main.navigation-view .mobile-navigation-panel session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
215
+ }
216
+ status-bar { flex: 0 0 auto; }
217
+ chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
218
+ prompt-editor, chat-composer { flex: 0 0 auto; }
219
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
220
+ .empty { margin: auto; color: var(--pi-muted); }
221
+ .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
222
+ @keyframes app-refresh-spin { to { transform: rotate(360deg); } }
223
+ `,eh=E`
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
+ header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
226
+ .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
227
+ .workspace-header-scroll-frame::before, .workspace-header-scroll-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 18px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
228
+ .workspace-header-scroll-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
229
+ .workspace-header-scroll-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
230
+ .workspace-header-scroll-frame.can-scroll-left::before, .workspace-header-scroll-frame.can-scroll-right::after { opacity: 1; }
231
+ .workspace-header-strip { display: flex; justify-content: space-between; align-items: center; gap: 8px; min-width: 0; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
232
+ .tabs { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; }
233
+ .tabs button { flex: 0 0 auto; white-space: nowrap; }
234
+ .tabs button.icon-tab { min-width: 34px; }
235
+ button { display: inline-flex; align-items: center; gap: 5px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; cursor: pointer; }
236
+ button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
237
+ .tab-icon { flex: 0 0 auto; width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
238
+ .tab-custom-icon { flex: 0 0 auto; width: 16px; height: 16px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
239
+ .tab-custom-icon svg { width: 16px; height: 16px; pointer-events: none; }
240
+ .tab-label { min-width: 0; }
241
+ .tab-badge { flex: 0 0 auto; display: inline-block; min-width: 14px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
242
+ @container (max-width: 430px) {
243
+ .tabs button.icon-tab { justify-content: center; padding-inline: 7px; }
244
+ .tabs button.icon-tab .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; }
245
+ }
246
+ .panel-content { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: auto; }
247
+ .empty-state { box-sizing: border-box; width: min(100%, 380px); margin: auto; padding: 24px; display: grid; gap: 8px; color: var(--pi-muted); text-align: center; }
248
+ .empty-state h2 { margin: 0; color: var(--pi-text); font-size: 15px; line-height: 1.3; }
249
+ .empty-state p { margin: 0; line-height: 1.45; }
250
+ small, .muted { color: var(--pi-muted); }
251
+ header small { flex: 0 0 auto; min-width: max-content; overflow: visible; text-overflow: clip; white-space: nowrap; }
252
+ header .workspace-label { width: max-content; max-width: none; overflow: visible; }
253
+ header .workspace-label-base, header .workspace-label-item, header .workspace-label-render { overflow: visible; text-overflow: clip; }
254
+ @media (max-width: 1180px) { .tabs { display: none; } }
255
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
256
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
257
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
258
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
259
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
260
+ .toolbar { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); }
261
+ .toolbar button { margin-left: auto; }
262
+ .stale { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); padding: 1px 6px; font-size: 12px; }
263
+ .split { flex: 1 1 auto; min-height: 0; display: grid; grid-template-rows: minmax(160px, 34%) minmax(0, 1fr); }
264
+ .list { min-height: 0; overflow: auto; border-bottom: 1px solid var(--pi-border); padding: 6px; }
265
+ .row { display: grid; grid-template-columns: 18px minmax(0, 1fr); gap: 4px; width: 100%; border: 0; border-radius: 5px; background: transparent; text-align: left; padding: 4px 6px 4px calc(6px + var(--depth, 0) * 14px); }
266
+ .row:hover, .row.selected { background: var(--pi-selection-bg); }
267
+ .row span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
268
+ .summary { margin: 4px 6px 8px; color: var(--pi-muted); }
269
+ .viewer { min-height: 0; overflow: auto; display: flex; flex-direction: column; }
270
+ .diffs { flex: 1 1 auto; min-height: 0; overflow: auto; display: grid; grid-template-rows: minmax(120px, 1fr) minmax(120px, 1fr); }
271
+ .diffs.single { grid-template-rows: minmax(0, 1fr); }
272
+ .diff-section { min-height: 0; display: flex; flex-direction: column; border-bottom: 1px solid var(--pi-border); }
273
+ .diff-section:last-child { border-bottom: 0; }
274
+ .viewer-header { position: sticky; top: 0; display: flex; justify-content: space-between; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
275
+ .viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
276
+ code-viewer { flex: 1 1 auto; min-height: 0; }
277
+ .image-preview { flex: 1 1 auto; min-height: 0; box-sizing: border-box; display: flex; align-items: center; justify-content: center; overflow: auto; padding: 16px; }
278
+ .image-preview img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; border: 1px solid var(--pi-border-muted); border-radius: 8px; background-color: var(--pi-surface); background-image: linear-gradient(45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(-45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%), linear-gradient(-45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%); background-position: 0 0, 0 8px, 8px -8px, -8px 0; background-size: 16px 16px; box-shadow: 0 8px 24px var(--pi-shadow-soft); }
279
+ pre { margin: 0; padding: 10px; overflow: auto; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
280
+ p { margin: 10px; }
281
+ `,mi=E`
282
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
283
+ :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
284
+ section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
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
+ .list-body { flex: 1 1 auto; min-height: 0; overflow: auto; }
287
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
288
+ section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
289
+ .subheading { margin-top: 14px; }
290
+ .section-toggle { display: flex; flex: 1 1 auto; min-width: 0; align-items: center; justify-content: space-between; gap: 8px; width: 100%; border: 0; background: transparent; color: inherit; padding: 0; font: inherit; text-align: left; text-transform: inherit; }
291
+ .section-toggle span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
292
+ .section-title { display: grid; gap: 2px; min-width: 0; }
293
+ .section-toggle .section-selected { display: block; color: var(--pi-text); font-size: 12px; font-weight: 600; line-height: 1.25; text-transform: none; }
294
+ .section-toggle .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
295
+ .section-toggle small { display: inline; color: inherit; font-size: inherit; }
296
+ .action-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 6px 0; cursor: pointer; }
297
+ .action-row:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; border-radius: 8px; }
298
+ .action-row.selected .action-main, .action-row.selected .action-menu-toggle { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
299
+ .action-row.archived .action-main { color: var(--pi-muted); }
300
+ .action-main { box-sizing: border-box; min-width: 0; width: 100%; border: 1px solid var(--pi-border); border-top-right-radius: 0; border-bottom-right-radius: 0; border-top-left-radius: 8px; border-bottom-left-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px 7px calc(9px + var(--depth, 0) * 16px); text-align: left; }
301
+ .action-name { display: -webkit-box; max-height: 2.5em; overflow: hidden; overflow-wrap: anywhere; line-height: 1.25; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
302
+ .action-row:not(.selected):hover .action-main { background: var(--pi-surface-hover); }
303
+ .workspace-row .action-main { border-radius: 8px 0 0 8px; }
304
+ .workspace-primary { min-width: 0; display: flex; align-items: baseline; gap: 6px; }
305
+ .workspace-primary .activity-indicator { flex: 0 0 auto; margin-right: 0; }
306
+ .workspace-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
307
+ .workspace-status { flex: 0 0 auto; color: var(--pi-warning); font-size: 12px; }
308
+ .workspace-secondary { margin-top: 3px; }
309
+ .workspace-menu-panel { width: max-content; min-width: min(120px, calc(100vw - 16px)); padding: 8px; }
310
+ .workspace-menu-actions { margin: 0 0 8px; padding-bottom: 8px; border-bottom: 1px solid var(--pi-border-muted); }
311
+ .workspace-menu-actions button.danger { color: var(--pi-danger); }
312
+ .workspace-menu-actions button.danger:hover, .workspace-menu-actions button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
313
+ .workspace-menu-details { display: grid; gap: 6px; margin: 0; }
314
+ .workspace-detail-row { display: grid; grid-template-columns: minmax(58px, max-content) minmax(0, 1fr); gap: 8px; align-items: baseline; }
315
+ .workspace-detail-row dt { color: var(--pi-muted); font-size: 12px; white-space: normal; }
316
+ .workspace-detail-row dd { min-width: 0; margin: 0; overflow-wrap: anywhere; white-space: normal; }
317
+ .tree-marker { color: var(--pi-dim); margin-right: 5px; }
318
+ .badge { display: inline-block; margin-left: 5px; border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); padding: 0 5px; font-size: 11px; font-weight: 400; }
319
+ .activity-indicator { display: inline-block; width: 7px; height: 7px; margin-right: 6px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; vertical-align: 1px; }
320
+ .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
321
+ .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
322
+ .action-menu { position: relative; align-self: stretch; }
323
+ .action-menu-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0; }
324
+ .action-menu-toggle:hover { color: var(--pi-text); background: var(--pi-surface-hover); }
325
+ .action-menu-panel { position: fixed; z-index: 50; box-sizing: border-box; min-width: min(120px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); overflow-wrap: anywhere; }
326
+ .action-menu-panel button { display: block; width: 100%; text-align: left; white-space: normal; overflow-wrap: anywhere; border: 0; background: transparent; color: var(--pi-text); }
327
+ .action-menu-panel button:hover { background: var(--pi-selection-bg); }
328
+ button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
329
+ button:disabled { opacity: .5; cursor: not-allowed; }
330
+ small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
331
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
332
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
333
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
334
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
335
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
336
+ .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
337
+ .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
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
339
+ `,th=E`
340
+ :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
+ .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
342
+ .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
343
+ .scroll-marker { display: block; height: 0; overflow: hidden; pointer-events: none; }
344
+ .activity-dock { position: absolute; left: 16px; right: 16px; bottom: 12px; z-index: 20; display: flex; align-items: center; gap: 8px; min-width: 0; box-sizing: border-box; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-bg-overlay); color: var(--pi-muted); padding: 8px 12px; font-size: 13px; pointer-events: none; box-shadow: 0 8px 28px var(--pi-shadow); backdrop-filter: blur(6px); }
345
+ .activity-dock.active { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-bg-overlay); }
346
+ .activity-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
347
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
348
+ .activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
349
+ .msg { max-width: 100%; min-width: 0; box-sizing: border-box; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); overflow: visible; }
350
+ .msg.user { border-color: var(--pi-accent-border); background: var(--pi-selection-bg); }
351
+ .msg.tool { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
352
+ .msg.tool-execution-shell { padding: 0; border: 0; background: transparent; color: var(--pi-text); }
353
+ .msg.system { color: var(--pi-danger); }
354
+ .msg.bash { border-color: var(--pi-success); background: var(--pi-success-bg); }
355
+ .msg.skill { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
356
+ .msg.event-group { padding: 0; border-color: var(--pi-border); background: var(--pi-bg); color: var(--pi-muted); }
357
+ .msg.event-group.live { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
358
+ .msg.event-group > summary { position: sticky; top: -26px; z-index: 5; display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 9px 9px 0 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); color: var(--pi-muted); }
359
+ .msg.event-group.live > summary { border-bottom-color: var(--pi-success-border); background: var(--pi-success-bg); color: var(--pi-success); }
360
+ .msg.event-group > summary .label { margin: 0; }
361
+ .group-body { padding: 0 12px 12px; }
362
+ .group-msg { max-width: 100%; min-width: 0; box-sizing: border-box; padding: 10px 0; border-top: 1px solid var(--pi-border-muted); color: var(--pi-text); overflow: visible; }
363
+ .group-msg.tool { color: var(--pi-warning); }
364
+ .group-msg.tool-execution-shell { color: var(--pi-text); }
365
+ .group-msg.system { color: var(--pi-danger); }
366
+ .group-msg.bash { color: var(--pi-success); }
367
+ .history-boundary { position: relative; z-index: 5; display: grid; gap: 3px; justify-items: center; margin: 0 0 14px; color: var(--pi-muted); font-size: 12px; text-align: center; }
368
+ .history-load-button { border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text-secondary); padding: 5px 12px; font: 12px system-ui, sans-serif; cursor: pointer; }
369
+ .history-load-button:hover, .history-load-button:focus { border-color: var(--pi-accent); color: var(--pi-text-bright); }
370
+ .history-load-button:disabled { cursor: default; opacity: .55; }
371
+ .queued-messages { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 8px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-warning-border); border-radius: 10px; background: var(--pi-warning-surface); color: var(--pi-text); overflow: hidden; }
372
+ .queued-header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
373
+ .queued-header strong { color: var(--pi-warning); }
374
+ .queued-header small { color: var(--pi-muted); }
375
+ .queued-message { display: grid; gap: 4px; padding-top: 8px; border-top: 1px solid var(--pi-border); }
376
+ .queued-message:first-of-type { padding-top: 0; border-top: 0; }
377
+ .queued-kind { color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
378
+ .session-activity { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 4px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); color: var(--pi-text); overflow: hidden; }
379
+ .session-activity.compacting { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
380
+ .session-activity.receiving { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
381
+ .session-activity strong { color: var(--pi-purple); }
382
+ .session-activity.receiving strong { color: var(--pi-success); }
383
+ .session-activity span, .session-activity small { color: var(--pi-muted); }
384
+ .history-boundary small { color: var(--pi-dim); }
385
+ .msg-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 22px; margin-bottom: 8px; }
386
+ .msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -12px -12px 8px; padding: 7px 10px 6px; border-radius: 9px 9px 0 0; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-surface); box-shadow: 0 8px 18px var(--pi-shadow-soft); }
387
+ .msg.user > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-accent-border) 35%, transparent); background: var(--pi-selection-bg); }
388
+ .msg.tool > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-warning-border) 35%, transparent); background: var(--pi-warning-surface); }
389
+ .msg.bash > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-success) 35%, transparent); background: var(--pi-success-bg); }
390
+ .msg.skill > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-purple-border) 35%, transparent); background: var(--pi-purple-surface); }
391
+ .group-msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -10px 0 8px; padding: 7px 0 6px; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-bg); }
392
+ .msg-header-trailing { min-width: 0; display: inline-flex; align-items: baseline; justify-content: flex-end; gap: 8px; }
393
+ .msg-actions { display: inline-flex; gap: 6px; opacity: 0; transition: opacity .12s ease; }
394
+ .msg-action { display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
395
+ .msg-action:hover, .msg-action:focus { color: var(--pi-text); border-color: var(--pi-accent); }
396
+ .msg:hover > .msg-header .msg-actions, .msg:focus-within > .msg-header .msg-actions, .group-msg:hover > .msg-header .msg-actions, .group-msg:focus-within > .msg-header .msg-actions { opacity: 1; }
397
+ .label { display: block; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
398
+ .msg-header .label { margin: 0; }
399
+ .msg-meta { min-width: 0; opacity: .28; border: 0; background: transparent; color: var(--pi-dim); padding: 0; font: 11px system-ui, sans-serif; text-align: right; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: opacity .12s ease, max-width .12s ease; cursor: pointer; user-select: text; -webkit-user-select: text; }
400
+ .msg:hover > .msg-header .msg-meta, .msg:focus-within > .msg-header .msg-meta, .group-msg:hover > .msg-header .msg-meta, .group-msg:focus-within > .msg-header .msg-meta, .msg-meta:focus, .msg-meta.expanded { opacity: 1; }
401
+ .msg-meta:focus { outline: 1px solid var(--pi-border); outline-offset: 3px; border-radius: 4px; }
402
+ @media (hover: none) {
403
+ .msg-actions { opacity: 1; }
404
+ .msg-meta { opacity: .75; max-width: 26px; }
405
+ .msg-meta::before { content: "ⓘ"; font-size: 13px; }
406
+ .msg-meta:focus, .msg-meta.expanded { opacity: 1; max-width: 75%; }
407
+ .msg-meta:focus::before, .msg-meta.expanded::before { content: ""; }
408
+ }
409
+ formatted-text.part { display: block; }
410
+ .part { max-width: 100%; min-width: 0; box-sizing: border-box; overflow: visible; }
411
+ .part + .part { margin-top: 10px; }
412
+ .tool-line { color: var(--pi-warning); }
413
+ .summary { color: var(--pi-muted); margin-left: 6px; }
414
+ .part:is(details) { border-top: 1px solid var(--pi-border); padding-top: 8px; }
415
+ .part > formatted-text { display: block; max-width: 100%; min-width: 0; overflow: visible; }
416
+ .skill-invocation, .skill-read { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); padding: 8px 10px; }
417
+ .skill-invocation > summary, .skill-read > strong { color: var(--pi-purple); }
418
+ .skill-invocation > small, .skill-read > small { display: block; margin: 6px 0 0; color: var(--pi-muted); }
419
+ summary { cursor: pointer; color: var(--pi-muted); }
420
+ pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
421
+ .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
422
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
423
+ `,ih=E`
424
+ :host { display: block; }
425
+ .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
426
+ p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
427
+ :is(p, ul, ol, pre, blockquote, table, .code-block-wrapper):last-child { margin-bottom: 0; }
428
+ ul, ol { padding-left: 22px; }
429
+ li + li { margin-top: 3px; }
430
+ code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-bg); padding: 1px 4px; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
431
+ .code-block-wrapper { position: relative; }
432
+ .code-block-wrapper pre { margin: 0; padding-right: 40px; }
433
+ pre { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 10px; overflow-x: auto; overflow-y: hidden; }
434
+ pre code { border: 0; padding: 0; background: transparent; }
435
+ .code-copy-button { position: absolute; top: 6px; right: 6px; z-index: 1; display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
436
+ .code-copy-button:hover, .code-copy-button:focus { color: var(--pi-text); border-color: var(--pi-accent); }
437
+ blockquote { border-left: 3px solid var(--pi-border); padding-left: 10px; color: var(--pi-muted); }
438
+ a { color: var(--pi-accent); }
439
+ h1, h2, h3, h4 { margin: 14px 0 8px; line-height: 1.2; }
440
+ h1:first-child, h2:first-child, h3:first-child, h4:first-child { margin-top: 0; }
441
+ h1 { font-size: 20px; }
442
+ h2 { font-size: 17px; }
443
+ h3 { font-size: 15px; }
444
+ h4 { font-size: 14px; }
445
+ table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
446
+ th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
447
+ th { background: var(--pi-surface); }
448
+ `,sh=E`
449
+ :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
450
+ .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
+ span { overflow: hidden; text-overflow: ellipsis; }
452
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
453
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
454
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
455
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
456
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
457
+ .bar > span:first-child { flex: 1 1 auto; min-width: 80px; }
458
+ .activity { display: inline-flex; align-items: center; gap: 6px; color: var(--pi-muted); }
459
+ .activity.active { color: var(--pi-success); }
460
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
461
+ .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
462
+ .muted { color: var(--pi-dim); }
463
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
464
+ `,rh=E`
465
+ :host { display: block; }
466
+ .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
+ 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; }
468
+ button:last-child { border-bottom: 0; }
469
+ button.selected, button:hover { background: var(--pi-selection-bg); }
470
+ span { color: var(--pi-muted); font-size: 12px; }
471
+ small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
472
+ `,Jo=E`
473
+ :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
474
+ .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
475
+ 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; }
476
+ header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
477
+ .options { min-height: 0; overflow: auto; outline: none; }
478
+ button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
479
+ header button { font-size: 20px; color: var(--pi-muted); }
480
+ input { margin: 10px 12px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); font: 14px system-ui, sans-serif; padding: 8px 10px; outline: none; }
481
+ input:focus { border-color: var(--pi-accent); }
482
+ .options button { display: block; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
483
+ .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
484
+ small { display: block; margin-top: 4px; color: var(--pi-muted); }
485
+ .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
486
+ `,oh=E`
487
+ :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
488
+ .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
+ 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; }
490
+ header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid var(--pi-border); }
491
+ input { min-width: 0; border: 0; outline: none; background: transparent; color: var(--pi-text); font: 16px system-ui, sans-serif; padding: 8px; }
492
+ input::placeholder { color: var(--pi-dim); }
493
+ button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
494
+ header button { color: var(--pi-muted); font-size: 22px; padding: 2px 8px; }
495
+ .options { flex: 1 1 auto; min-height: 0; overflow: auto; }
496
+ .options button { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 3px 12px; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
497
+ .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
498
+ .main { min-width: 0; }
499
+ strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
500
+ small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
501
+ .group { grid-column: 1 / -1; font-size: 12px; }
502
+ 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
+ .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
504
+ `,nh=E`
505
+ :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
506
+ footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
507
+ footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
508
+ .editor-wrap { position: relative; min-width: 0; }
509
+ .actions { display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: nowrap; white-space: nowrap; }
510
+ .compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: var(--pi-muted); font-size: 12px; flex: 1 1 0; }
511
+ .compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
512
+ .select-model { max-width: min(42vw, 320px); }
513
+ .select-thinking { max-width: 110px; }
514
+ textarea, .markdown-editor .cm-editor { box-sizing: border-box; width: 100%; min-height: 54px; max-height: 220px; resize: none; overflow: hidden; border-radius: 8px; border: 1px solid var(--pi-border); background: var(--pi-bg); color: var(--pi-text); font: 16px/1.4 system-ui, sans-serif; }
515
+ textarea { overflow-y: auto; padding: 8px; }
516
+ .markdown-editor .cm-scroller { max-height: 220px; overflow-y: auto; font-family: system-ui, sans-serif; line-height: 1.4; }
517
+ .markdown-editor .cm-content { min-height: 38px; padding: 8px; caret-color: var(--pi-text); }
518
+ .markdown-editor .cm-line { padding: 0; }
519
+ .markdown-editor .cm-placeholder { color: var(--pi-dim); }
520
+ .markdown-editor .cm-focused { outline: none; }
521
+ .shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: var(--pi-success); box-shadow: 0 0 0 1px var(--pi-success-ring); }
522
+ .mode-hint { position: absolute; right: 8px; bottom: 8px; max-width: calc(100% - 16px); border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 2px 8px; font-size: 12px; pointer-events: none; }
523
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
524
+ button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
525
+ @media (max-width: 640px) {
526
+ footer { gap: 8px; padding: 8px; }
527
+ .actions { gap: 6px; }
528
+ .compact-status { flex: 1 1 220px; gap: 4px; }
529
+ .select-model { max-width: min(58vw, 260px); }
530
+ button { padding: 6px 8px; }
531
+ }
532
+ @media (max-width: 430px) {
533
+ .compact-status { flex-basis: 170px; font-size: 11px; }
534
+ .select-model { max-width: 48vw; }
535
+ .select-thinking { max-width: 70px; }
536
+ button { padding: 5px 7px; }
537
+ }
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`
539
+ <section>
540
+ <h2>${this.renderHeading()}</h2>
541
+ ${this.collapsed?null:l`
542
+ <div class="list-body">
543
+ ${this.machines.map(e=>this.renderMachine(e))}
544
+ </div>
545
+ `}
546
+ </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`
548
+ <div
549
+ class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
550
+ tabindex="0"
551
+ title=${e.baseUrl??e.name}
552
+ @click=${r=>{ui(r,()=>this.onSelect?.(e))}}
553
+ @keydown=${r=>{this.handleMachineKeydown(r,e)}}
554
+ >
555
+ <div class="action-main">
556
+ <span class="action-name machine-primary">${this.renderActivity(e)}<span class="machine-primary-label">${e.name}</span></span><small>${e.kind==="local"?"本机 Pi Web":e.baseUrl??"远程 Pi Web"} · ${i}</small>
557
+ </div>
558
+ ${s?this.renderMachineMenu(e):null}
559
+ </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`
561
+ <div class="action-menu">
562
+ <button
563
+ class="action-menu-toggle"
564
+ title="机器操作"
565
+ aria-label=${`${e.name} 的操作`}
566
+ aria-expanded=${String(t)}
567
+ aria-controls=${i}
568
+ @click=${s=>{s.stopPropagation(),this.toggleMenu(e.id,s.currentTarget)}}
569
+ >⋯</button>
570
+ ${t?l`
571
+ <div class="action-menu-panel machine-menu-panel" id=${i} style=${this.menuStyle} @click=${s=>{s.stopPropagation()}}>
572
+ <button class="danger" title=${`移除 ${e.name}`} @click=${()=>{this.removeMachine(e)}}>移除</button>
573
+ </div>
574
+ `:null}
575
+ </div>
576
+ `}renderHeading(){if(!this.collapsible)return"机器";const e=this.selected?.name??"未选择机器",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 机器</span><small class="section-selected" title=${t}>${e}</small></span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=Pt(t),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}fi(e,()=>this.onSelect?.(t))}};V.styles=[mi,E`
577
+ .machine-row.no-actions .action-main { border-radius: 8px; }
578
+ .machine-primary { display: flex; align-items: baseline; gap: 6px; }
579
+ .machine-primary .activity-indicator { flex: 0 0 auto; margin-right: 0; }
580
+ .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
581
+ .machine-menu-panel button.danger { color: var(--pi-danger); }
582
+ .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`
584
+ <section>
585
+ <h2>${this.renderHeading()}</h2>
586
+ ${this.collapsed?null:l`
587
+ <div class="list-body">
588
+ ${this.projects.map(e=>l`
589
+ <div
590
+ class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
591
+ tabindex="0"
592
+ title=${e.path}
593
+ @click=${t=>{ui(t,()=>this.onSelect?.(e))}}
594
+ @keydown=${t=>{fi(t,()=>this.onSelect?.(e))}}
595
+ >
596
+ <div class="action-main">
597
+ <span class="action-name">${e.name}</span><small>${this.renderActivity(e)}${e.path}</small>
598
+ </div>
599
+ <div class="action-menu">
600
+ <button class="action-menu-toggle" title="项目操作" aria-label=${`${e.name} 的操作`} @click=${t=>{t.stopPropagation(),this.toggleMenu(e.id,t.currentTarget)}}>⋯</button>
601
+ ${this.openMenuProjectId===e.id?l`
602
+ <div class="action-menu-panel" style=${this.menuStyle}>
603
+ <button title="关闭项目" @click=${()=>{this.close(e)}}>关闭</button>
604
+ </div>
605
+ `:null}
606
+ </div>
607
+ </div>
608
+ `)}
609
+ </div>
610
+ `}
611
+ </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}?
613
+
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`
615
+ <span class="workspace-label">
616
+ <span class="workspace-label-base" title=${i??e}>${e}</span>
617
+ ${uh(t)}
618
+ </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`
620
+ <section>
621
+ <h2>${this.renderHeading()}</h2>
622
+ ${this.collapsed?null:l`
623
+ <div class="list-body">
624
+ ${this.workspaces.map(e=>{const t=vh(e),i=this.workspaceLabelItems(e);return l`
625
+ <div
626
+ class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
627
+ tabindex="0"
628
+ title=${t}
629
+ @click=${s=>{ui(s,()=>this.onSelect?.(e))}}
630
+ @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
631
+ >
632
+ <div class="action-main">
633
+ ${this.renderWorkspaceMain(t,i,e)}
634
+ </div>
635
+ ${this.renderWorkspaceMenu(t,i,e)}
636
+ </div>
637
+ `})}
638
+ </div>
639
+ `}
640
+ </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`
642
+ <span class="workspace-primary">
643
+ ${this.renderActivity(i)}
644
+ <span class="workspace-primary-label">${e}</span>
645
+ ${this.isDeleting(i)?l`<span class="workspace-status">正在删除…</span>`:null}
646
+ </span>
647
+ ${t.length===0?null:l`
648
+ <small class="workspace-secondary">
649
+ <span class="workspace-label">${kr(t)}</span>
650
+ </small>
651
+ `}
652
+ `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,r=wh(i.id);return l`
653
+ <div class="action-menu">
654
+ <button
655
+ class="action-menu-toggle"
656
+ title="工作区操作和详情"
657
+ aria-label=${`${e} 的操作和详情`}
658
+ aria-expanded=${String(s)}
659
+ aria-controls=${r}
660
+ @click=${o=>{o.stopPropagation(),this.toggleMenu(i.id,o.currentTarget)}}
661
+ >⋯</button>
662
+ ${s?l`
663
+ <div class="action-menu-panel workspace-menu-panel" id=${r} style=${this.menuStyle} @click=${o=>{o.stopPropagation()}}>
664
+ ${this.renderWorkspaceActions(i)}
665
+ ${this.renderWorkspaceDetails(e,t,i)}
666
+ </div>
667
+ `:null}
668
+ </div>
669
+ `}renderWorkspaceActions(e){if(!bh(e))return;const t=this.isDeleting(e);return l`
670
+ <div class="workspace-menu-actions">
671
+ <button class="danger" title=${t?"正在删除工作区":"删除工作区"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"正在删除…":"删除工作区"}</button>
672
+ </div>
673
+ `}renderWorkspaceDetails(e,t,i){return l`
674
+ <dl class="workspace-menu-details">
675
+ <div class="workspace-detail-row">
676
+ <dt>${i.branch===void 0?"工作区":"分支"}</dt>
677
+ <dd>${e}</dd>
678
+ </div>
679
+ <div class="workspace-detail-row">
680
+ <dt>路径</dt>
681
+ <dd title=${i.path}>${i.path}</dd>
682
+ </div>
683
+ ${t.length===0?null:l`
684
+ <div class="workspace-detail-row">
685
+ <dt>详情</dt>
686
+ <dd><span class="workspace-label">${kr(t)}</span></dd>
687
+ </div>
688
+ `}
689
+ </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`
691
+ <section>
692
+ ${this.renderHeading(e.length+i.length)}
693
+ ${this.collapsed?null:l`
694
+ <div class="list-body">
695
+ ${e.map(r=>this.renderSession(r,s.get(r.session.id)??0))}
696
+ ${i.length>0?l`
697
+ <h2 class="subheading"><button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} 已归档</span><small>${i.length}</small></button></h2>
698
+ ${this.archivedExpanded?i.map(r=>this.renderSession(r,s.get(r.session.id)??0)):null}
699
+ `:null}
700
+ </div>
701
+ `}
702
+ </section>
703
+ `}renderHeading(e){if(!this.collapsible)return l`<h2>会话 <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button></h2>`;const t=this.selected===void 0?"未选择会话":Ai(this.selected),i=this.selected?.path??t;return l`
704
+ <h2>
705
+ <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=${i}>${t}</small></span><small class="section-count">${e}</small></button>
706
+ <button ?disabled=${!this.canStart} @click=${s=>{s.stopPropagation(),this.onStart?.()}}>+</button>
707
+ </h2>
708
+ `}renderSession(e,t){const{session:i}=e,s=Math.min(e.depth,2);return l`
709
+ <div
710
+ class="action-row ${this.selected?.id===i.id?"selected":""} ${i.archived===!0?"archived":""}"
711
+ style=${`--depth:${String(s)}`}
712
+ tabindex="0"
713
+ title=${i.path}
714
+ @click=${r=>{ui(r,()=>this.onSelect?.(i))}}
715
+ @keydown=${r=>{fi(r,()=>this.onSelect?.(i))}}
716
+ >
717
+ <div class="action-main">
718
+ <span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Ai(i)}${e.depth>2?l` <span class="badge">深度 ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">父会话不可用</span>`:null}</span><small>${this.renderStatus(i)}${String(i.messageCount)} 条消息</small>
719
+ </div>
720
+ <div class="action-menu">
721
+ <button class="action-menu-toggle" title="会话操作" @click=${r=>{r.stopPropagation(),this.toggleMenu(i.id,r.currentTarget)}}>⋯</button>
722
+ ${this.openMenuSessionId===i.id?l`
723
+ <div class="action-menu-panel" style=${this.menuStyle}>
724
+ ${i.parentSessionPath!==void 0?l`<button title="从父会话分离" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(i)}}>从父会话分离</button>`:null}
725
+ ${ke(i)?l`<button title="删除浏览器缓存的新会话" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(i)}}>删除</button>`:i.archived===!0?l`<button title="恢复会话" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(i)}}>恢复</button>`:l`
726
+ <button title="归档会话" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(i)}}>归档</button>
727
+ ${t>0?l`<button title="归档此会话及其子会话" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(i,t)}}>连同子会话归档(${t})</button>`:null}
728
+ `}
729
+ </div>
730
+ `:null}
731
+ </div>
732
+ </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`
734
+ <div
735
+ class="meter"
736
+ style=${`--position:${e.toFixed(2)}%;`}
737
+ role="meter"
738
+ aria-label=${i}
739
+ aria-valuemin="0"
740
+ aria-valuemax="100"
741
+ aria-valuenow=${String(Math.round(e))}
742
+ title=${i}
743
+ >
744
+ <div class="track" aria-hidden="true">
745
+ <div class="progress"></div>
746
+ <div class="marker"></div>
747
+ </div>
748
+ </div>
749
+ `}};yt.styles=E`
750
+ :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
751
+ :host(:hover), :host(:focus-within) { opacity: .92; }
752
+ .meter { height: 100%; }
753
+ .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
+ .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
+ .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(`
758
+ `),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(`
760
+ `).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],`
762
+ `),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
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Me(t[0],`
764
+ `).split(`
765
+ `),s="",r="",o=[];for(;i.length>0;){let n=!1,a=[],c;for(c=0;c<i.length;c++)if(this.rules.other.blockquoteStart.test(i[c]))a.push(i[c]),n=!0;else if(!n)a.push(i[c]);else break;i=i.slice(c);let p=a.join(`
766
+ `),f=p.replace(this.rules.other.blockquoteSetextReplace,`
767
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
768
+ ${p}`:p,r=r?`${r}
769
+ ${f}`:f;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(f,o,!0),this.lexer.state.top=h,i.length===0)break;let u=o.at(-1);if(u?.type==="code")break;if(u?.type==="blockquote"){let v=u,S=v.raw+`
770
+ `+i.join(`
771
+ `),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
+ `+i.join(`
773
+ `),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(`
775
+ `,1)[0],t[1].length),u=e.split(`
776
+ `,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+=`
780
+ `+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(`
783
+ `):[],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],`
785
+ `),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,`
787
+ `),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
+ `: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
+ `)?"":`
790
+ `)+o.raw,a.text+=`
791
+ `+o.text,this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
792
+ `)?"":`
793
+ `)+o.raw,a.text+=`
794
+ `+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},i.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),i.push(o);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,c=t.slice(1),p;this.options.extensions.startBlock.forEach(f=>{p=f.call({lexer:this},c),typeof p=="number"&&p>=0&&(a=Math.min(a,p))}),a<1/0&&a>=0&&(n=t.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
795
+ `)?"":`
796
+ `)+o.raw,a.text+=`
797
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o),s=n.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
798
+ `)?"":`
799
+ `)+o.raw,a.text+=`
800
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)o=r[2]?r[2].length:0,s=s.slice(0,r.index+o)+"["+"a".repeat(r[0].length-o-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let f=t;if(this.options.extensions?.startInline){let h=1/0,u=t.slice(1),v;this.options.extensions.startInline.forEach(S=>{v=S.call({lexer:this},u),typeof v=="number"&&v>=0&&(h=Math.min(h,v))}),h<1/0&&h>=0&&(f=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(f)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},ai=class{options;parser;constructor(e){this.options=e||Ue}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(H.notSpaceStart)?.[0],r=e.replace(H.endingNewline,"")+`
801
+ `;return s?'<pre><code class="language-'+ge(s)+'">'+(i?r:ge(r,!0))+`</code></pre>
802
+ `:"<pre><code>"+(i?r:ge(r,!0))+`</code></pre>
803
+ `}blockquote({tokens:e}){return`<blockquote>
804
+ ${this.parser.parse(e)}</blockquote>
805
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
806
+ `}hr(e){return`<hr>
807
+ `}list(e){let t=e.ordered,i=e.start,s="";for(let n=0;n<e.items.length;n++){let a=e.items[n];s+=this.listitem(a)}let r=t?"ol":"ul",o=t&&i!==1?' start="'+i+'"':"";return"<"+r+o+`>
808
+ `+s+"</"+r+`>
809
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
810
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
811
+ `}table(e){let t="",i="";for(let r=0;r<e.header.length;r++)i+=this.tablecell(e.header[r]);t+=this.tablerow({text:i});let s="";for(let r=0;r<e.rows.length;r++){let o=e.rows[r];i="";for(let n=0;n<o.length;n++)i+=this.tablecell(o[n]);s+=this.tablerow({text:i})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
812
+ <thead>
813
+ `+t+`</thead>
814
+ `+s+`</table>
815
+ `}tablerow({text:e}){return`<tr>
816
+ ${e}</tr>
817
+ `}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`
820
+ <section class=${`tool-card ${e.status}`}>
821
+ <div class="tool-header">
822
+ <div class="tool-title">
823
+ <span class="status-icon" aria-hidden="true">${ff(e.status)}</span>
824
+ <strong>${e.toolName}</strong>
825
+ ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
826
+ </div>
827
+ <div class="tool-meta">
828
+ ${Br(e)===void 0?null:l`<span>${Br(e)}</span>`}
829
+ ${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>
831
+ </div>
832
+ </div>
833
+
834
+ ${a?l`<p class="notice">实际应用的 diff 与预览不同。</p>`:null}
835
+ ${c===void 0||c===""?null:l`<pre class="error-text">${c}</pre>`}
836
+ ${o===void 0?this.renderTextBody(p,e.status==="error"):this.renderDiffBody(o,s===void 0?"预览 diff":"已应用 diff")}
837
+ ${!t&&o===void 0&&(p===void 0||p==="")?l`<p class="muted">${e.summary}</p>`:null}
838
+ </section>
839
+ `}renderTextBody(e,t){return e===void 0||e===""?null:l`
840
+ <details class="text-body" ?open=${t}>
841
+ <summary>结果</summary>
842
+ <pre>${e}</pre>
843
+ </details>
844
+ `}renderDiffBody(e,t){const i=e.split(`
845
+ `),s=!this.showFullDiff&&i.length>Nr,r=s?i.slice(0,Nr):i;return l`
846
+ <details class="diff-details" ?open=${this.diffOpen} @toggle=${o=>{this.onDiffToggle(o)}}>
847
+ <summary>
848
+ <span>${t}</span>
849
+ <small>${String(i.length)} 行</small>
850
+ </summary>
851
+ <div class="diff-toolbar">
852
+ <span>${s?`显示 ${String(r.length)} / ${String(i.length)} 行`:"完整 diff"}</span>
853
+ <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"已复制":"复制 diff"}</button>
854
+ </div>
855
+ <pre class="diff" aria-label=${t}><code class="diff-content">${r.map(o=>l`<span class=${uf(o)}>${o}</span>`)}</code></pre>
856
+ ${s?l`
857
+ <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
858
+ 显示全部 ${String(i.length)} 行 diff
859
+ </button>
860
+ `:null}
861
+ </details>
862
+ `}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){try{await navigator.clipboard.writeText(e),this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}catch{this.copied=!1}}};Be.styles=E`
863
+ :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
864
+ .tool-card { display: grid; gap: 8px; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 9px; color: var(--pi-text); }
865
+ .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
866
+ .tool-card.success { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
867
+ .tool-card.error { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); }
868
+ .tool-header { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; min-width: 0; }
869
+ .tool-title { display: inline-flex; align-items: baseline; gap: 7px; min-width: 0; }
870
+ .status-icon { flex: 0 0 auto; color: var(--pi-muted); }
871
+ strong { color: var(--pi-text); }
872
+ .path, .summary { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-accent); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
873
+ .summary { color: var(--pi-muted); font-family: inherit; }
874
+ .tool-meta { flex: 0 0 auto; display: inline-flex; align-items: baseline; gap: 8px; color: var(--pi-muted); font-size: 12px; }
875
+ .diff-stats { display: inline-flex; gap: 3px; }
876
+ .added, .diff .added { color: var(--pi-success); }
877
+ .removed, .diff .removed { color: var(--pi-danger); }
878
+ .status-label { text-transform: uppercase; letter-spacing: .04em; color: var(--pi-muted); }
879
+ .notice { margin: 0; color: var(--pi-warning); }
880
+ .muted { margin: 0; color: var(--pi-muted); }
881
+ .error-text { margin: 0; border: 1px solid var(--pi-danger); border-radius: 7px; background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); color: var(--pi-danger); padding: 8px; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
882
+ .text-body { border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
883
+ .text-body pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--pi-text); }
884
+ .diff-details { min-width: 0; max-width: 100%; border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
885
+ .diff-details > summary { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; min-width: 0; color: var(--pi-muted); cursor: pointer; }
886
+ .diff-details > summary span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
887
+ .diff-details > summary small { flex: 0 0 auto; color: var(--pi-dim); }
888
+ .diff-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-width: 0; margin-top: 8px; color: var(--pi-muted); font-size: 12px; }
889
+ .diff-toolbar span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
890
+ button { border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-text); padding: 3px 7px; font: 12px system-ui, sans-serif; cursor: pointer; }
891
+ button:hover, button:focus { border-color: var(--pi-accent); }
892
+ .diff { box-sizing: border-box; width: 100%; max-width: 100%; min-width: 0; margin: 0; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; border: 1px solid var(--pi-border-muted); border-radius: 7px; background: var(--pi-bg); padding: 8px 0; color: var(--pi-muted); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
893
+ .diff-content { display: block; width: max-content; min-width: 100%; }
894
+ .diff span { display: block; min-height: 1.45em; padding: 0 8px; white-space: pre; }
895
+ .diff .context { color: var(--pi-muted); }
896
+ .diff .hunk { color: var(--pi-accent); }
897
+ .diff .file { color: var(--pi-dim); }
898
+ .diff .meta { color: var(--pi-dim); }
899
+ .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
900
+ .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
901
+ .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`
904
+ <div class="chat-wrap">
905
+ ${this.renderConversationRail()}
906
+ <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
907
+ ${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)))}
909
+ ${this.renderQueuedMessages()}
910
+ ${this.renderSessionActivity()}
911
+ </div>
912
+ ${this.renderActivityDock()}
913
+ </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`
915
+ <div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
916
+ <span class="dot"></span>
917
+ <span class="activity-text">${this.activityText(e)}</span>
918
+ </div>
919
+ `}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return e.length===0?null:l`
920
+ <aside class="queued-messages" aria-live="polite">
921
+ <div class="queued-header">
922
+ <strong>排队消息</strong>
923
+ <small>${e.length} 条待处理 · 停止会清空队列</small>
924
+ </div>
925
+ ${e.map((t,i)=>l`
926
+ <div class="queued-message">
927
+ <span class="queued-kind">${t.kind==="steer"?"引导":"跟进"} ${String(i+1)}</span>
928
+ <formatted-text .text=${t.text}></formatted-text>
929
+ </div>
930
+ `)}
931
+ </aside>
932
+ `}renderSessionActivity(){return this.isReceivingPartialStream?l`
933
+ <aside class="session-activity receiving" aria-live="polite">
934
+ <strong>正在同步…</strong>
935
+ <span>${this.currentPartialStreamNoticeBody()}</span>
936
+ </aside>
937
+ `:this.isCompacting?l`
938
+ <aside class="session-activity compacting" aria-live="polite">
939
+ <strong>正在压缩历史…</strong>
940
+ <span>助手正在总结早前上下文。压缩完成前,新提示会排队等待。</span>
941
+ ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} 条消息已排队</small>`:null}
942
+ </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`
944
+ <div class="history-boundary">
945
+ <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载更早的消息</button>
946
+ <span>向上滚动加载更早的消息</span>
947
+ ${e}
948
+ </div>
949
+ `:this.messages.length?l`<div class="history-boundary"><span>会话开始</span>${e}</div>`:null}historyRangeLabel(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.messageStart+1,t=this.loadedRawMessageEnd(),i=Math.max(this.messageTotal,t);return l`<small>显示消息 ${e}–${t} / ${i}</small>`}loadedRawMessageEnd(){return Math.max(this.messageEnd,this.messageStart+this.messages.length)}renderMessage(e,t){const i=this.isToolExecutionOnlyMessage(e);return l`
950
+ ${this.renderScrollMarker(this.messageScrollMarkerId(t))}
951
+ <article class=${i?"msg tool-execution-shell":`msg ${e.role}`} data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
952
+ ${i?null:this.renderMessageHeader(e,String(t))}
953
+ ${e.parts.map(s=>this.renderPart(s,e))}
954
+ </article>
955
+ `}isToolExecutionOnlyMessage(e){return e.role==="tool"&&e.parts.length>0&&e.parts.every(t=>t.type==="toolExecution")}renderMessageGroup(e,t,i,s){const r=this.groupDisclosureKey(t,i,s),o=this.disclosures.isOpen(r,s);return l`
956
+ ${this.renderScrollMarker(this.groupScrollMarkerId(i))}
957
+ <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
+ <summary>
959
+ <b class="label">${s?"实时事件":"事件"}</b>
960
+ <span>${Oh(e)}</span>
961
+ </summary>
962
+ <div class="group-body">
963
+ ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
964
+ <section class=${c?"group-msg tool-execution-shell":`group-msg ${n.role}`} data-index=${t+a} data-scroll-anchor-id=${this.eventAnchorKey(t+a)}>
965
+ ${c?null:this.renderMessageHeader(n,`${String(t)}:${String(a)}`)}
966
+ ${n.parts.map(p=>this.renderPart(p,n))}
967
+ </section>
968
+ `})}
969
+ </div>
970
+ </details>
971
+ `}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
+ <div class="msg-header">
973
+ <b class="label">${Ur(e.role)}</b>
974
+ <div class="msg-header-trailing">
975
+ ${this.renderMessageActions(e,t)}
976
+ <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>
977
+ </div>
978
+ </div>
979
+ `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
980
+ <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)}}>
982
+ <span aria-hidden="true">${i?"✓":"⧉"}</span>
983
+ </button>
984
+ </div>
985
+ `}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
+
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`
988
+ <details class="part skill-invocation">
989
+ <summary><b>[技能]</b> ${e.name}</summary>
990
+ <small>${e.location}</small>
991
+ <formatted-text .text=${e.content}></formatted-text>
992
+ </details>
993
+ `:e.type==="skillRead"?l`
994
+ <div class="part skill-read">
995
+ <strong>已加载 ${e.name}</strong>
996
+ <small>读取 ${e.path}</small>
997
+ </div>
998
+ `:e.type==="toolCall"?l`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type==="toolExecution"?l`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type==="toolResult"?l`
999
+ <details class="part" ?open=${e.isError}>
1000
+ <summary>${e.isError?"✖":"✓"} ${e.toolName} 结果</summary>
1001
+ <formatted-text .text=${e.text}></formatted-text>
1002
+ </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`
1004
+ <div class="menu">
1005
+ ${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)}}>
1007
+ <strong>${e.insertText}</strong>
1008
+ <span>${e.detail}</span>
1009
+ ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1010
+ </button>
1011
+ `)}
1012
+ </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`
1014
+ <footer class=${t?"shell-mode":""}>
1015
+ <div class="editor-wrap">
1016
+ <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"}></div>
1017
+ ${t?l`<div class="mode-hint">Shell 命令${e.excludeFromContext?" · 不加入上下文":""}</div>`:null}
1018
+ ${this.isCompacting&&!t?l`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
1019
+ <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${s=>{this.pick(s)}}></autocomplete-menu>
1020
+ </div>
1021
+ <div class="actions">
1022
+ ${this.renderCompactStatus()}
1023
+ <button ?disabled=${this.disabled} title=${i?"当前活动结束后排队发送":"发送消息"} @click=${()=>{this.send("followUp")}}>${i?"排队":"发送"}</button>
1024
+ ${this.canSteer&&!this.isCompacting?l`<button ?disabled=${this.disabled} title="在下一次模型调用前引导当前回复" @click=${()=>{this.send("steer")}}>引导</button>`:null}
1025
+ <button ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} @click=${()=>this.onStop?.()}>停止</button>
1026
+ </div>
1027
+ </footer>
1028
+ `}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
+ <div class="compact-status" aria-label="会话状态">
1030
+ <button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1031
+ <button class="select-thinking" title="选择思考级别" @click=${()=>this.onSelectThinking?.()}>思考 ${Af(e.thinkingLevel)}</button>
1032
+ </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`
1035
+ <div class="bar">
1036
+ <span>${this.machine?.name??"本机"}</span>
1037
+ <span>${Qo(this.workspace?.label??"工作区",this.workspaceLabelItems,this.workspace?.path)}</span>
1038
+ <span>↑${Wt(s.input)}</span>
1039
+ <span>↓${Wt(s.output)}</span>
1040
+ <span>${i}</span>
1041
+ <span>${_f(e.cost)}</span>
1042
+ ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} 条排队</span>`:null}
1043
+ </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`
1045
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1046
+ <section @mousedown=${t=>{t.stopPropagation()}}>
1047
+ <header>
1048
+ <strong>${this.title}</strong>
1049
+ <button @click=${()=>this.onCancel?.()}>×</button>
1050
+ </header>
1051
+ ${this.searchable?l`<input placeholder="搜索" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1052
+ <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1053
+ ${e.map((t,i)=>l`
1054
+ <button class=${i===this.selectedIndex?"selected":""} ${Rs(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1055
+ <span>${t.label}</span>
1056
+ ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1057
+ </button>
1058
+ `)}
1059
+ ${e.length===0?l`<div class="empty">没有匹配选项</div>`:null}
1060
+ </div>
1061
+ </section>
1062
+ </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`
1064
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1065
+ <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1066
+ <header>
1067
+ <input
1068
+ .value=${this.queryText}
1069
+ placeholder="搜索操作..."
1070
+ @input=${t=>{t.target instanceof HTMLInputElement&&(this.queryText=t.target.value,this.selectedIndex=0)}}
1071
+ >
1072
+ <button title="关闭" @click=${()=>this.onCancel?.()}>×</button>
1073
+ </header>
1074
+ <div class="options">
1075
+ ${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)}}>
1077
+ <span class="main">
1078
+ <strong>${t.title}</strong>
1079
+ ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1080
+ </span>
1081
+ ${t.shortcut!==void 0?l`<kbd>${Mo(t.shortcut)}</kbd>`:null}
1082
+ ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1083
+ </button>
1084
+ `)}
1085
+ </div>
1086
+ </section>
1087
+ </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`
1089
+ <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1090
+ <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1091
+ <header>
1092
+ <strong>${this.dialogTitle(e)}</strong>
1093
+ <button title="关闭" @click=${()=>{this.cancel()}}>×</button>
1094
+ </header>
1095
+ ${this.renderBody(e)}
1096
+ </section>
1097
+ </div>
1098
+ `}updated(){this.focusInputIfNeeded()}dialogTitle(e){switch(e.step){case"method":return"配置提供商认证";case"providers":return e.authType===void 0?"选择提供商认证":e.authType==="oauth"?"选择订阅提供商":"选择 API key 提供商";case"apiKey":return`${e.provider.name} 的 API key`;case"oauth":return`登录 ${e.flow.providerName}`;case"logout":return"移除已保存的提供商认证"}}renderBody(e){switch(e.step){case"method":return l`
1099
+ <div class="options">
1100
+ <button @click=${()=>{this.onChooseMethod?.("oauth")}}><span>使用订阅</span><small>ChatGPT Plus/Pro、Claude Pro/Max 或 GitHub Copilot</small></button>
1101
+ <button @click=${()=>{this.onChooseMethod?.("api_key")}}><span>使用 API key</span><small>将 API key 存入 pi auth.json</small></button>
1102
+ </div>
1103
+ `;case"providers":return l`<div class="options">${e.providers.length===0?l`<div class="empty">没有可用提供商。</div>`:e.providers.map(t=>this.renderProviderButton(t))}</div>`;case"apiKey":return l`
1104
+ <div class="form">
1105
+ <p>输入 <strong>${e.provider.name}</strong> 的 API key。它会由 pi 存入 <code>auth.json</code>。</p>
1106
+ <input type="password" autocomplete="off" placeholder="API key" .value=${e.value} @input=${t=>{t.target instanceof HTMLInputElement&&this.onApiKeyInput?.(t.target.value)}}>
1107
+ ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1108
+ <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
+ </div>
1110
+ `;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>
1112
+ `)}</div>`}}renderProviderButton(e){return l`
1113
+ <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>
1116
+ </button>
1117
+ `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1118
+ <div class="form">
1119
+ ${t.auth!==void 0?l`
1120
+ <p>打开此授权链接:</p>
1121
+ <p><a href=${t.auth.url} target="_blank" rel="noreferrer">${t.auth.url}</a></p>
1122
+ ${t.auth.instructions!==void 0?l`<p class="warning">${t.auth.instructions}</p>`:null}
1123
+ `:l`<p>正在启动登录流程…</p>`}
1124
+ ${t.progress.length>0?l`<ul class="progress">${t.progress.map(r=>l`<li>${r}</li>`)}</ul>`:null}
1125
+ ${i!==void 0?l`
1126
+ <label>${i.message}</label>
1127
+ <input .value=${e.inputValue??""} placeholder=${i.placeholder??""} @input=${r=>{r.target instanceof HTMLInputElement&&this.onOAuthInput?.(r.target.value)}}>
1128
+ <div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button><button class="primary" ?disabled=${e.responding===!0} @click=${()=>{this.onOAuthRespond?.()}}>提交</button></div>
1129
+ `:null}
1130
+ ${s!==void 0?l`
1131
+ <p>${s.message}</p>
1132
+ <div class="inline-options">${s.options.map(r=>l`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
1133
+ `:null}
1134
+ ${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}
1136
+ ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
1137
+ </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`
1139
+ .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1140
+ .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1141
+ .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
1142
+ .form code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-surface); padding: 1px 4px; }
1143
+ label { color: var(--pi-muted); }
1144
+ .actions { display: flex; justify-content: flex-end; gap: 8px; }
1145
+ .actions button, .inline-options button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; }
1146
+ .actions button.primary { border-color: var(--pi-success-border); background: var(--pi-success-surface); color: var(--pi-success); }
1147
+ .actions button:disabled { opacity: .6; cursor: wait; }
1148
+ .warning { color: var(--pi-warning); }
1149
+ .error-text { color: var(--pi-danger); }
1150
+ .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1151
+ .inline-options { display: grid; gap: 8px; }
1152
+ 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`
1154
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
1155
+ <section @click=${e=>{e.stopPropagation()}}>
1156
+ <header>
1157
+ <strong>添加项目</strong>
1158
+ <button @click=${()=>{this.onCancel?.()}} aria-label="关闭">×</button>
1159
+ </header>
1160
+ <div class="body">
1161
+ <label>
1162
+ 项目文件夹
1163
+ <input .value=${this.path} @input=${e=>{this.onPathInput(e)}} @keydown=${e=>{this.onKeyDown(e)}} placeholder="/path/to/project or ~/code/project" autofocus />
1164
+ </label>
1165
+ <div class="suggestions">
1166
+ ${this.loading?l`<div class="hint">正在加载文件夹…</div>`:null}
1167
+ ${this.suggestions.map((e,t)=>l`
1168
+ <button class=${t===this.selected?"selected":""} @click=${()=>{this.pick(e)}}>
1169
+ ${e.path}
1170
+ </button>
1171
+ `)}
1172
+ ${!this.loading&&this.suggestions.length===0?l`<div class="hint">没有匹配的文件夹。输入新路径即可创建。</div>`:null}
1173
+ </div>
1174
+ <label class="check">
1175
+ <input type="checkbox" .checked=${this.createMissing} @change=${e=>{this.onCreateMissingChange(e)}} />
1176
+ 如果文件夹不存在则创建
1177
+ </label>
1178
+ </div>
1179
+ <footer>
1180
+ <button @click=${()=>{this.onCancel?.()}}>取消</button>
1181
+ <button class="primary" ?disabled=${this.path.trim()===""} @click=${()=>{this.submit()}}>添加项目</button>
1182
+ </footer>
1183
+ </section>
1184
+ </div>
1185
+ `}};te.styles=E`
1186
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1187
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1188
+ section { width: min(720px, calc(100vw - 40px)); max-height: min(700px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
1189
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1190
+ footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1191
+ .body { display: grid; gap: 12px; padding: 12px; min-height: 0; }
1192
+ label { display: grid; gap: 6px; color: var(--pi-muted); }
1193
+ input[type="text"], input:not([type]) { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: 14px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1194
+ .check { display: flex; grid-template-columns: auto 1fr; align-items: center; color: var(--pi-text); }
1195
+ .suggestions { min-height: 90px; max-height: 320px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); }
1196
+ .suggestions button { display: block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1197
+ .suggestions button.selected, .suggestions button:hover { background: var(--pi-selection-bg); }
1198
+ .hint { padding: 12px; color: var(--pi-muted); }
1199
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1200
+ header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1201
+ .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1202
+ 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`
1204
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
1205
+ <section @click=${s=>{s.stopPropagation()}}>
1206
+ <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
1207
+ <header>
1208
+ <strong>添加机器</strong>
1209
+ <button type="button" @click=${()=>{this.onCancel?.()}} aria-label="关闭">×</button>
1210
+ </header>
1211
+ <div class="body">
1212
+ ${this.error===""?null:l`<div class="dialog-error" role="alert">${this.error}</div>`}
1213
+ <label>
1214
+ 远程 PI WEB URL
1215
+ <input name="baseUrl" type="url" .value=${this.url} @input=${s=>{this.handleUrlInput(s)}} placeholder="http://dev-box.local:8504" autocomplete="url" inputmode="url" autofocus />
1216
+ </label>
1217
+ <small class=${t===void 0?"hint":"field-error"}>${t??"先输入可访问的基础 URL,包含 http:// 或 https://。"}</small>
1218
+ ${e?l`
1219
+ <label>
1220
+ 机器名称
1221
+ <input name="name" type="text" .value=${this.name} @input=${s=>{this.handleNameInput(s)}} placeholder=${this.previousSuggestedName||"开发机"} autocomplete="off" />
1222
+ </label>
1223
+ <small class="hint">根据 URL 自动建议。可以改成更友好的侧栏名称。</small>
1224
+ <label>
1225
+ Bearer token <span class="optional">可选</span>
1226
+ <input name="token" type="password" .value=${this.token} @input=${s=>{this.handleTokenInput(s)}} placeholder="如果远程机器不需要 token,可留空" autocomplete="off" />
1227
+ </label>
1228
+ <small class="hint">只粘贴 token 值;PI WEB 会通过 Authorization: Bearer 请求头发送。</small>
1229
+ `:l`<p class="hint intro">输入 URL 后,PI WEB 会建议机器名称,并允许添加可选的 bearer token。</p>`}
1230
+ </div>
1231
+ <footer>
1232
+ <button type="button" @click=${()=>{this.onCancel?.()}}>取消</button>
1233
+ <button class="primary" type="submit" ?disabled=${!i}>${this.submitting?"正在添加…":"添加机器"}</button>
1234
+ </footer>
1235
+ </form>
1236
+ </section>
1237
+ </div>
1238
+ `}};ie.styles=E`
1239
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1240
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1241
+ section { width: min(560px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
1242
+ form { display: flex; flex-direction: column; max-height: inherit; min-height: 0; }
1243
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1244
+ footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1245
+ .body { display: grid; gap: 8px; padding: 12px; min-height: 0; overflow: auto; }
1246
+ label { display: grid; gap: 6px; color: var(--pi-muted); }
1247
+ input { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: 14px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1248
+ input:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 1px; }
1249
+ .hint { color: var(--pi-muted); }
1250
+ .intro { margin: 4px 0 0; line-height: 1.4; }
1251
+ .optional { color: var(--pi-muted); font-weight: 400; }
1252
+ .field-error { color: var(--pi-danger); }
1253
+ .dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; }
1254
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1255
+ header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1256
+ .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1257
+ 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`
1260
+ <div class="section-heading">
1261
+ <div>
1262
+ <h2>通用配置</h2>
1263
+ <p>更新 PI WEB 正在使用的 JSON 配置文件。Host 和端口会立即保存,但需要重启 Web 服务后,运行中的服务器才会绑定到新地址。</p>
1264
+ </div>
1265
+ <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>重新加载</button>
1266
+ </div>
1267
+ ${this.renderMessages()}
1268
+ ${e===void 0&&this.loading?l`<div class="loading-card">正在加载配置…</div>`:l`
1269
+ <div class="config-path-card">
1270
+ <span>配置文件</span>
1271
+ <code>${e?.path??"未知"}</code>
1272
+ <small>${e?.exists===!0?"已有文件":"保存时会创建此文件"}</small>
1273
+ </div>
1274
+ <form class="config-form" @submit=${t=>{this.saveConfig(t)}}>
1275
+ <label class="field">
1276
+ <span class="field-heading">
1277
+ <span>Host</span>
1278
+ ${this.renderOverrideBadge("host")}
1279
+ </span>
1280
+ <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:Vr(t)})}}>
1281
+ <small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
1282
+ </label>
1283
+
1284
+ <label class="field">
1285
+ <span class="field-heading">
1286
+ <span>Port</span>
1287
+ ${this.renderOverrideBadge("port")}
1288
+ </span>
1289
+ <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:Vr(t)})}}>
1290
+ <small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
1291
+ </label>
1292
+
1293
+ <div class="field">
1294
+ <span class="field-heading">
1295
+ <span>允许的 hosts</span>
1296
+ ${this.renderOverrideBadge("allowedHosts")}
1297
+ </span>
1298
+ <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:om(t)==="all"?"all":"list"})}}>
1299
+ <option value="list">仅允许列出的 hosts</option>
1300
+ <option value="all">允许所有 host</option>
1301
+ </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>
1303
+ <small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
1304
+ </div>
1305
+
1306
+ ${this.renderEffectiveConfig()}
1307
+
1308
+ <footer class="form-actions">
1309
+ <button class="primary" ?disabled=${this.loading||this.saving}>${this.saving?"正在保存…":"保存配置"}</button>
1310
+ </footer>
1311
+ </form>
1312
+ `}
1313
+ `}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderOverrideBadge(e){return this.configResponse?.envOverrides[e]!==!0?null:l`<span class="override-badge">环境变量覆盖</span>`}renderEffectiveConfig(){const e=this.configResponse?.effectiveConfig??{};return l`
1314
+ <section class="effective-card" aria-label="最终生效配置摘要">
1315
+ <h3>环境变量覆盖后的生效配置</h3>
1316
+ <dl>
1317
+ <div><dt>Host</dt><dd>${e.host??l`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
1318
+ <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>
1320
+ </dl>
1321
+ </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`
1323
+ :host { display: block; }
1324
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1325
+ .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1326
+ h2, h3, p { margin: 0; }
1327
+ h2 { font-size: 17px; line-height: 1.25; }
1328
+ h3 { font-size: 13px; line-height: 1.3; }
1329
+ p { color: var(--pi-muted); line-height: 1.45; }
1330
+ button, input, select, textarea { font: inherit; }
1331
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1332
+ button:disabled { opacity: .55; cursor: not-allowed; }
1333
+ .secondary { flex: 0 0 auto; }
1334
+ .message, .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1335
+ .message { margin-bottom: 12px; }
1336
+ .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1337
+ .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1338
+ .loading-card { color: var(--pi-muted); }
1339
+ .config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
1340
+ .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1341
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1342
+ .config-path-card small, .field small { color: var(--pi-muted); }
1343
+ .config-form { display: grid; gap: 14px; }
1344
+ .field { display: grid; gap: 7px; }
1345
+ .field-heading { display: flex; align-items: center; gap: 8px; }
1346
+ input, select, textarea { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px 10px; outline: none; }
1347
+ input:focus, select:focus, textarea:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1348
+ textarea { resize: vertical; min-height: 94px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1349
+ textarea:disabled { opacity: .55; }
1350
+ .override-badge { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); background: var(--pi-warning-surface); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: none; }
1351
+ .effective-card { display: grid; gap: 10px; }
1352
+ .effective-card dl { display: grid; gap: 8px; margin: 0; }
1353
+ .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
1354
+ dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
1355
+ .muted { color: var(--pi-muted); }
1356
+ .form-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
1357
+ .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
1358
+
1359
+ @media (max-width: 760px) {
1360
+ .section-heading { display: grid; gap: 12px; }
1361
+ .section-heading .secondary { justify-self: start; }
1362
+ .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1363
+ }
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`
1365
+ <div class="section-heading">
1366
+ <div>
1367
+ <h2>插件</h2>
1368
+ <p>启用或禁用已发现的 PI WEB 插件。更改会在重新加载浏览器标签页后生效;当前页面已加载的插件代码不会被卸载。</p>
1369
+ </div>
1370
+ <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>重新加载</button>
1371
+ </div>
1372
+ ${this.renderMessages()}
1373
+ <div class="plugin-note">配置键:<code>plugins</code>。除非条目将 <code>enabled</code> 设置为 <code>false</code>,插件默认启用。</div>
1374
+ ${this.loading&&e.length===0?l`<div class="loading-card">正在加载插件…</div>`:e.length===0?l`<div class="loading-card">未发现外部或内置插件。</div>`:l`
1375
+ <div class="plugin-list">
1376
+ ${e.map(t=>this.renderPlugin(t))}
1377
+ </div>
1378
+ `}
1379
+ `}renderMessages(){return this.error!==""?l`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage} 重新加载浏览器标签页以应用插件更改。</div>`:null}renderPlugin(e){const t=this.configResponse?.config.plugins?.[e.id],i=t?.enabled===!1?"配置已禁用":t?.enabled===!0?"配置已启用":"默认启用";return l`
1380
+ <article class=${`plugin-card${e.enabled?"":" disabled"}`}>
1381
+ <div class="plugin-main">
1382
+ <strong>${e.id}</strong>
1383
+ <small>${e.source} · ${e.scope}</small>
1384
+ <small>${i}</small>
1385
+ </div>
1386
+ <label class="toggle">
1387
+ <input type="checkbox" .checked=${e.enabled} ?disabled=${this.saving} @change=${s=>{this.togglePlugin(e,s)}}>
1388
+ <span>${e.enabled?"已启用":"已禁用"}</span>
1389
+ </label>
1390
+ </article>
1391
+ `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};me.styles=E`
1392
+ :host { display: block; }
1393
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1394
+ .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1395
+ h2, p { margin: 0; }
1396
+ h2 { font-size: 17px; line-height: 1.25; }
1397
+ p { color: var(--pi-muted); line-height: 1.45; }
1398
+ button, input { font: inherit; }
1399
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1400
+ button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
1401
+ .secondary { flex: 0 0 auto; }
1402
+ .message, .loading-card, .plugin-note, .plugin-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1403
+ .message { margin-bottom: 12px; }
1404
+ .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1405
+ .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1406
+ .loading-card, .plugin-note { color: var(--pi-muted); }
1407
+ .plugin-note { margin-bottom: 14px; }
1408
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1409
+ .plugin-list { display: grid; gap: 10px; }
1410
+ .plugin-card { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center; }
1411
+ .plugin-card.disabled { opacity: .75; }
1412
+ .plugin-main { min-width: 0; display: grid; gap: 3px; }
1413
+ .plugin-main strong, .plugin-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1414
+ .plugin-main small { color: var(--pi-muted); }
1415
+ .toggle { display: inline-flex; align-items: center; gap: 7px; white-space: nowrap; }
1416
+ .toggle input { width: 18px; height: 18px; accent-color: var(--pi-accent); }
1417
+
1418
+ @media (max-width: 760px) {
1419
+ .section-heading { display: grid; gap: 12px; }
1420
+ .section-heading .secondary { justify-self: start; }
1421
+ .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1422
+ .toggle { justify-self: start; }
1423
+ }
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`
1425
+ <div class="section-heading">
1426
+ <div>
1427
+ <h2>键盘快捷键</h2>
1428
+ <p>查看已注册的应用操作和快捷键配置。手动配置项使用 action id,可以覆盖默认快捷键,或设置为 <code>null</code> 以禁用。</p>
1429
+ </div>
1430
+ </div>
1431
+ <div class="shortcut-note">配置键:<code>shortcuts</code>。示例:<code>{ "core:view.chat": "mod+1", "core:session.stop": null }</code></div>
1432
+ ${e.length===0?l`<div class="loading-card">没有已注册操作。</div>`:e.map(t=>l`
1433
+ <section class="shortcut-group">
1434
+ <h3>${t.name}</h3>
1435
+ <div class="shortcut-list">
1436
+ ${t.actions.map(i=>this.renderShortcutRow(i))}
1437
+ </div>
1438
+ </section>
1439
+ `)}
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`
1441
+ <div class="shortcut-row">
1442
+ <div class="shortcut-main">
1443
+ <strong>${e.title}</strong>
1444
+ ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1445
+ <small class="shortcut-id">${e.id}</small>
1446
+ </div>
1447
+ <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>
1450
+ </div>
1451
+ </div>
1452
+ `}};xt.styles=E`
1453
+ :host { display: block; }
1454
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1455
+ .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1456
+ h2, h3, p { margin: 0; }
1457
+ h2 { font-size: 17px; line-height: 1.25; }
1458
+ h3 { font-size: 13px; line-height: 1.3; }
1459
+ p { color: var(--pi-muted); line-height: 1.45; }
1460
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1461
+ .loading-card, .shortcut-note { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1462
+ .loading-card, .shortcut-note { color: var(--pi-muted); }
1463
+ .shortcut-note { margin-bottom: 14px; }
1464
+ .shortcut-group { margin: 0 0 16px; }
1465
+ .shortcut-group h3 { margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
1466
+ .shortcut-list { border: 1px solid var(--pi-border); border-radius: 10px; overflow: hidden; }
1467
+ .shortcut-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; align-items: center; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-surface); }
1468
+ .shortcut-row:last-child { border-bottom: 0; }
1469
+ .shortcut-main { min-width: 0; display: grid; gap: 3px; }
1470
+ .shortcut-main strong, .shortcut-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1471
+ .shortcut-main small { color: var(--pi-muted); }
1472
+ .shortcut-id { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1473
+ .shortcut-value { justify-self: end; display: grid; justify-items: end; gap: 3px; }
1474
+ kbd { justify-self: end; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-bg); color: var(--pi-text-secondary); padding: 3px 7px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
1475
+ .unassigned { justify-self: end; color: var(--pi-muted); font-size: 12px; }
1476
+ .shortcut-value small { color: var(--pi-muted); font-size: 11px; }
1477
+ .shortcut-value small.custom { color: var(--pi-accent); }
1478
+ .shortcut-value small.disabled { color: var(--pi-warning); }
1479
+
1480
+ @media (max-width: 760px) {
1481
+ .section-heading { display: grid; gap: 12px; }
1482
+ .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1483
+ .shortcut-value { justify-self: start; justify-items: start; }
1484
+ kbd, .unassigned { justify-self: start; }
1485
+ }
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`
1487
+ <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1488
+ <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1489
+ <header class="settings-header">
1490
+ <div>
1491
+ <span class="eyebrow">设置</span>
1492
+ <h1>PI WEB</h1>
1493
+ </div>
1494
+ <button class="close-button" title="关闭设置" aria-label="关闭设置" @click=${()=>this.onClose?.()}>×</button>
1495
+ </header>
1496
+ <div class="settings-body">
1497
+ <nav class="settings-nav" aria-label="设置分区">
1498
+ ${this.renderNavButton("general","通用","服务器配置")}
1499
+ ${this.renderNavButton("plugins","插件","启用和禁用")}
1500
+ ${this.renderNavButton("shortcuts","键盘","快捷键")}
1501
+ </nav>
1502
+ <main class="settings-content">
1503
+ ${this.renderActiveSection()}
1504
+ </main>
1505
+ </div>
1506
+ </section>
1507
+ </div>
1508
+ `}renderActiveSection(){return this.section==="shortcuts"?l`<settings-shortcuts-panel .actions=${this.actions} .configResponse=${this.configResponse}></settings-shortcuts-panel>`:this.section==="plugins"?l`
1509
+ <settings-plugins-panel
1510
+ .configResponse=${this.configResponse}
1511
+ .pluginsResponse=${this.pluginsResponse}
1512
+ .loading=${this.loading}
1513
+ .saving=${this.saving}
1514
+ .error=${this.error}
1515
+ .savedMessage=${this.savedMessage}
1516
+ .onReload=${()=>this.loadConfig()}
1517
+ .onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
1518
+ ></settings-plugins-panel>
1519
+ `:l`
1520
+ <settings-general-panel
1521
+ .configResponse=${this.configResponse}
1522
+ .loading=${this.loading}
1523
+ .saving=${this.saving}
1524
+ .error=${this.error}
1525
+ .savedMessage=${this.savedMessage}
1526
+ .onReload=${()=>this.loadConfig()}
1527
+ .onSave=${e=>this.saveConfig(e)}
1528
+ ></settings-general-panel>
1529
+ `}renderNavButton(e,t,i){const s=this.section===e;return l`
1530
+ <button class=${s?"selected":""} aria-current=${s?"page":"false"} @click=${()=>{this.navigate(e)}}>
1531
+ <strong>${t}</strong>
1532
+ <small>${i}</small>
1533
+ </button>
1534
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([Qt.config(),zi.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${Wi(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},r=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...r,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await Qt.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${Wi(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await zi.plugins()}catch(e){this.error=`刷新插件失败:${Wi(e)}`}}showSavedMessage(){this.savedMessage="配置已保存。",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="配置已保存。"&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};J.styles=E`
1535
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1536
+ .backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
1537
+ .settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
1538
+ .settings-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
1539
+ .eyebrow { display: block; color: var(--pi-muted); font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
1540
+ h1 { margin: 0; font-size: 20px; line-height: 1.2; }
1541
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; font: inherit; cursor: pointer; }
1542
+ .close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
1543
+ .close-button:hover, .close-button:focus { color: var(--pi-text); background: var(--pi-surface-hover); }
1544
+ .settings-body { min-height: 0; display: grid; grid-template-columns: 220px minmax(0, 1fr); }
1545
+ .settings-nav { min-height: 0; padding: 10px; border-right: 1px solid var(--pi-border); background: var(--pi-surface); overflow: auto; }
1546
+ .settings-nav button { display: grid; gap: 2px; width: 100%; margin: 0 0 6px; text-align: left; border-color: transparent; background: transparent; }
1547
+ .settings-nav button:hover, .settings-nav button:focus { background: var(--pi-surface-hover); }
1548
+ .settings-nav button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1549
+ .settings-nav small { color: var(--pi-muted); }
1550
+ .settings-content { min-width: 0; min-height: 0; overflow: auto; padding: 18px; }
1551
+
1552
+ @media (max-width: 760px) {
1553
+ .backdrop { padding: 0; place-items: stretch; }
1554
+ .settings-shell { width: 100%; height: 100dvh; max-height: none; min-height: 0; border: 0; border-radius: 0; }
1555
+ .settings-header { padding: max(12px, env(safe-area-inset-top)) 12px 12px; }
1556
+ .settings-body { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
1557
+ .settings-nav { display: flex; gap: 8px; padding: 8px; border-right: 0; border-bottom: 1px solid var(--pi-border); overflow-x: auto; overflow-y: hidden; }
1558
+ .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
1559
+ .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
1560
+ }
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`
1562
+ <header>
1563
+ <div class=${this.workspaceHeaderFrameClass()}>
1564
+ <div class="workspace-header-strip" @scroll=${this.onWorkspaceHeaderScroll}>
1565
+ ${this.hideToolTabs?null:l`
1566
+ <div class="tabs">
1567
+ ${i.map(r=>{const o=s?.id===r.id,n=r.badge?.(t),a=this.panelTabAriaLabel(r,n);return l`
1568
+ <button class=${this.panelTabClass(r,o)} title=${a} aria-label=${a} aria-pressed=${String(o)} @click=${()=>{this.onSelectTool(r.id)}}>
1569
+ ${this.renderPanelTabContent(r,n)}
1570
+ </button>
1571
+ `})}
1572
+ </div>
1573
+ `}
1574
+ <small>${Qo(e.label,this.workspaceLabelItems,e.path)}</small>
1575
+ </div>
1576
+ </div>
1577
+ </header>
1578
+ ${s===void 0?this.renderEmptyState({title:"没有可用的工作区工具",body:"此工作区没有可用工具。"}):l`
1579
+ <div class="panel-content">
1580
+ ${s.render(t)}
1581
+ </div>
1582
+ `}
1583
+ `}panelTabClass(e,t){return[...e.icon===void 0?[]:["icon-tab"],...t?["selected"]:[]].join(" ")}panelTabAriaLabel(e,t){if(typeof t!="string"&&typeof t!="number")return e.title;const i=String(t).trim();return i===""?e.title:`${e.title}, ${i}`}renderPanelTabContent(e,t){return l`
1584
+ ${e.icon===void 0?null:l`<span class="tab-custom-icon" aria-hidden="true">${e.icon}</span>`}
1585
+ <span class="tab-label">${e.title}</span>
1586
+ ${this.isEmptyBadge(t)?null:l`<span class="tab-badge">${t}</span>`}
1587
+ `}isEmptyBadge(e){return e===void 0||e===""}renderEmptyState(e){return l`
1588
+ <section class="empty-state" role="status">
1589
+ <h2>${e.title}</h2>
1590
+ ${e.body===void 0?null:l`<p>${e.body}</p>`}
1591
+ </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`
1593
+ <nav class=${this.contextBarClass()} aria-label="当前位置">
1594
+ <span class="context-bar-label">位置</span>
1595
+ <ol class="context-items" @scroll=${this.onContextScroll}>
1596
+ <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")}}>
1598
+ <span class="context-kind">机器</span>
1599
+ ${this.renderMachineActivity()}
1600
+ <span class="context-value">${e}</span>
1601
+ </button>
1602
+ </li>
1603
+ <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")}}>
1605
+ <span class="context-kind">项目</span>
1606
+ <span class="context-value">${t}</span>
1607
+ </button>
1608
+ </li>
1609
+ <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")}}>
1611
+ <span class="context-kind">工作区</span>
1612
+ <span class="context-value">${i}</span>
1613
+ </button>
1614
+ </li>
1615
+ <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")}}>
1617
+ <span class="context-kind">会话</span>
1618
+ <span class="context-value">${s}</span>
1619
+ </button>
1620
+ </li>
1621
+ </ol>
1622
+ ${this.hasContextActions()?l`<div class="context-actions">${this.renderActionsButton()}${this.refreshControl}</div>`:null}
1623
+ </nav>
1624
+ `}renderMachineActivity(){return Tt(this.machineActivityKind,this.machineActivityKind==="terminal"?"机器终端活跃":"机器活跃")}renderActionsButton(){return this.onShowActions===void 0?null:l`
1625
+ <button type="button" class="context-action-button" title="显示操作" aria-label="显示操作" @click=${e=>{e.stopPropagation(),this.onShowActions?.()}}>
1626
+ <svg class="context-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1627
+ <path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
1628
+ </svg>
1629
+ </button>
1630
+ `}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};Z.styles=E`
1631
+ /* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
1632
+ :host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
1633
+ .context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: flex; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
1634
+ .context-bar::before, .context-bar::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
1635
+ .context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1636
+ .context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1637
+ .context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
1638
+ .context-bar-label { display: none; }
1639
+ .context-items { flex: 1 1 auto; min-width: 0; display: flex; align-items: stretch; gap: 5px; margin: 0; padding: 0 8px; list-style: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scroll-padding-inline: 8px; scrollbar-width: thin; }
1640
+ .context-bar.has-context-actions .context-items { padding-right: 58px; scroll-padding-inline: 8px 58px; }
1641
+ .context-bar.has-context-actions-double .context-items { padding-right: 102px; scroll-padding-inline: 8px 102px; }
1642
+ .context-item { flex: 0 0 auto; min-width: 0; display: flex; }
1643
+ .context-actions { position: absolute; top: 6px; right: 0; bottom: 6px; z-index: 3; display: flex; align-items: center; gap: 6px; padding: 0 8px; background: var(--pi-bg); pointer-events: none; }
1644
+ .context-actions::before { content: ""; position: absolute; top: 0; bottom: 0; left: -24px; z-index: 0; width: 24px; background: linear-gradient(90deg, transparent, var(--pi-bg)); pointer-events: none; }
1645
+ app-refresh-control, .context-action-button { position: relative; z-index: 1; pointer-events: auto; }
1646
+ .context-action-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; }
1647
+ .context-action-button:hover, .context-action-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1648
+ .context-action-icon { width: 18px; height: 18px; fill: currentColor; pointer-events: none; }
1649
+ .context-chip { flex: 0 0 auto; min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 8px; font: inherit; text-align: left; }
1650
+ .context-chip:hover { background: var(--pi-surface-hover); }
1651
+ .context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
1652
+ .context-chip.empty { border-style: dashed; color: var(--pi-muted); }
1653
+ .activity-indicator { flex: 0 0 auto; display: inline-block; width: 7px; height: 7px; margin-right: 0; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; vertical-align: 1px; }
1654
+ .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
1655
+ .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
1656
+ .context-kind { display: none; }
1657
+ .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
1658
+ button { cursor: pointer; }
1659
+ @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`
1661
+ <div class=${this.frameClass()}>
1662
+ <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
1663
+ ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
1664
+ <button class=${this.tabClass(t)} title=${t.label} aria-label=${this.tabAriaLabel(t)} aria-pressed=${String(i)} @click=${()=>{this.onSelect?.(t.id)}}>
1665
+ ${this.renderTabMark(t,e)}
1666
+ <span class="tab-label">${t.label}</span>
1667
+ ${this.isEmptyBadge(t.badge)?null:l`<span class="tab-badge">${t.badge}</span>`}
1668
+ </button>
1669
+ `})}
1670
+ </div>
1671
+ </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`
1673
+ :host { flex: 0 0 auto; min-width: 0; }
1674
+ .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
+ .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; }
1676
+ .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1677
+ .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1678
+ .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
1679
+ .mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
1680
+ .mobile-tabs button { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
1681
+ .mobile-tabs .navigation-tab { display: none; }
1682
+ .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1683
+ .tab-icon { flex: 0 0 auto; width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
1684
+ .tab-custom-icon { flex: 0 0 auto; width: 18px; height: 18px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
1685
+ .tab-custom-icon svg { width: 18px; height: 18px; pointer-events: none; }
1686
+ .tab-fallback { display: none; font-weight: 650; letter-spacing: .01em; pointer-events: none; }
1687
+ .tab-label { min-width: 0; }
1688
+ .tab-badge { flex: 0 0 auto; display: inline-block; min-width: 14px; margin-left: 0; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
1689
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1690
+ @media (max-width: 760px) {
1691
+ .mobile-tabs { gap: 4px; padding: 6px 8px; }
1692
+ .mobile-tabs button { min-width: 40px; height: 36px; justify-content: center; gap: 4px; padding: 0 8px; }
1693
+ .mobile-tabs .navigation-tab { display: inline-flex; }
1694
+ .tab-fallback { display: inline-block; }
1695
+ .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
+ .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
1697
+ }
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`
1699
+ <header>
1700
+ <strong>PI WEB</strong>
1701
+ <div class="header-actions">
1702
+ ${this.refreshControl}
1703
+ <button title="显示操作" aria-label="显示操作" @click=${()=>{this.onShowActions?.()}}>操作</button>
1704
+ </div>
1705
+ </header>
1706
+ ${_m(this.machines)?l`
1707
+ <machine-list
1708
+ .machines=${this.machines}
1709
+ .selected=${this.selectedMachine}
1710
+ .statuses=${this.machineStatuses}
1711
+ .activities=${this.machineActivities}
1712
+ .collapsible=${this.collapsible}
1713
+ .collapsed=${this.machinesCollapsed}
1714
+ .onToggleCollapsed=${()=>{this.onToggleMachines?.()}}
1715
+ .onSelect=${e=>this.onSelectMachine?.(e)}
1716
+ .onRemove=${e=>this.onRemoveMachine?.(e)}
1717
+ ></machine-list>
1718
+ `:null}
1719
+ <project-list
1720
+ .projects=${this.projects}
1721
+ .selected=${this.selectedProject}
1722
+ .activities=${this.workspaceActivities}
1723
+ .workspacesByProjectId=${this.workspacesByProjectId}
1724
+ .collapsible=${this.collapsible}
1725
+ .collapsed=${this.projectsCollapsed}
1726
+ .onToggleCollapsed=${()=>{this.onToggleProjects?.()}}
1727
+ .onSelect=${e=>this.onSelectProject?.(e)}
1728
+ .onClose=${e=>this.onCloseProject?.(e)}
1729
+ ></project-list>
1730
+ <workspace-list
1731
+ .workspaces=${this.workspaces}
1732
+ .selected=${this.selectedWorkspace}
1733
+ .activities=${this.workspaceActivities}
1734
+ .deletingWorkspaceIds=${this.deletingWorkspaceIds}
1735
+ .collapsible=${this.collapsible}
1736
+ .collapsed=${this.workspacesCollapsed}
1737
+ .workspaceLabelItems=${this.workspaceLabelItems}
1738
+ .onToggleCollapsed=${()=>{this.onToggleWorkspaces?.()}}
1739
+ .onSelect=${e=>this.onSelectWorkspace?.(e)}
1740
+ .onDelete=${e=>this.onDeleteWorkspace?.(e)}
1741
+ ></workspace-list>
1742
+ <session-list
1743
+ .sessions=${this.sessions}
1744
+ .statuses=${this.sessionStatuses}
1745
+ .activities=${this.sessionActivities}
1746
+ .selected=${this.selectedSession}
1747
+ .canStart=${this.canStartSession}
1748
+ .collapsible=${this.collapsible}
1749
+ .collapsed=${this.sessionsCollapsed}
1750
+ .onToggleCollapsed=${()=>{this.onToggleSessions?.()}}
1751
+ .onArchivedCollapsed=${()=>this.onArchivedCollapsed?.()}
1752
+ .onStart=${()=>this.onStartSession?.()}
1753
+ .onSelect=${e=>this.onSelectSession?.(e)}
1754
+ .onArchive=${e=>this.onArchiveSession?.(e)}
1755
+ .onArchiveWithDescendants=${e=>this.onArchiveSessionWithDescendants?.(e)}
1756
+ .onRestore=${e=>this.onRestoreSession?.(e)}
1757
+ .onDelete=${e=>this.onDeleteCachedNewSession?.(e)}
1758
+ .onDetachParent=${e=>this.onDetachParentSession?.(e)}
1759
+ ></session-list>
1760
+ `}};P.styles=E`
1761
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
1762
+ :host([collapsible]) { flex: 1 1 auto; }
1763
+ header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1764
+ :host([collapsible]) header { display: none; }
1765
+ .header-actions { display: flex; align-items: center; gap: 8px; }
1766
+ machine-list, project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
1767
+ session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
1768
+ :host([collapsible]) machine-list,
1769
+ :host([collapsible]) project-list,
1770
+ :host([collapsible]) workspace-list,
1771
+ :host([collapsible]) session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
1772
+ :host([collapsible]) machine-list[collapsed],
1773
+ :host([collapsible]) project-list[collapsed],
1774
+ :host([collapsible]) workspace-list[collapsed],
1775
+ :host([collapsible]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
1776
+ 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`
1778
+ <button
1779
+ type="button"
1780
+ class="edge-button"
1781
+ title=${e}
1782
+ aria-label=${e}
1783
+ aria-controls=${this.controls}
1784
+ aria-expanded=${String(!this.collapsed)}
1785
+ @click=${()=>{this.onToggle?.()}}
1786
+ >${this.renderIcon()}</button>
1787
+ `}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}};Te.styles=E`
1788
+ :host { min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
1789
+ :host([side="navigation"]) { grid-column: 2; }
1790
+ :host([side="workspace"]) { grid-column: 4; }
1791
+ .edge-button { position: relative; z-index: 1; box-sizing: border-box; display: grid; place-items: center; width: 18px; height: 48px; padding: 0; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-bg); color: var(--pi-muted); opacity: .75; cursor: pointer; }
1792
+ .edge-button:hover, .edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
1793
+ :host([side="navigation"][collapsed]) .edge-button { transform: translateX(calc(50% - .5px)); }
1794
+ :host([side="workspace"][collapsed]) .edge-button { transform: translateX(calc(-50% + .5px)); }
1795
+ .edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
1796
+ @media (max-width: 1180px) {
1797
+ :host([side="navigation"]) { grid-row: 1 / 3; }
1798
+ :host([side="workspace"]) { display: none; }
1799
+ }
1800
+ @media (max-width: 760px) {
1801
+ :host([side="navigation"]) { display: none; }
1802
+ }
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`
1804
+ <button
1805
+ class=${`app-refresh-button${this.isRefreshing?" refreshing":""}`}
1806
+ title=${e}
1807
+ aria-label=${e}
1808
+ aria-haspopup="menu"
1809
+ aria-expanded=${String(this.menuOpen)}
1810
+ aria-busy=${String(this.isRefreshing)}
1811
+ @click=${this.onRefreshClick}
1812
+ @contextmenu=${this.onRefreshContextMenu}
1813
+ @pointerdown=${this.onRefreshPointerDown}
1814
+ @pointerup=${()=>{this.clearLongPressTimer()}}
1815
+ @pointercancel=${()=>{this.clearLongPressTimer()}}
1816
+ @pointerleave=${()=>{this.clearLongPressTimer()}}
1817
+ >${this.renderRefreshIcon()}</button>
1818
+ `}renderRefreshIcon(){return l`
1819
+ <svg class="app-refresh-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1820
+ <path d="M20 6v5h-5"></path>
1821
+ <path d="M4 18v-5h5"></path>
1822
+ <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
1823
+ <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
1824
+ </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`
1826
+ :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
+ :host, :host * { -webkit-user-select: none; user-select: none; }
1828
+ .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
+ .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
1830
+ .app-refresh-button.refreshing .app-refresh-icon { animation: app-refresh-spin .8s linear infinite; }
1831
+ @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=`
1833
+ .pi-web-app-refresh-menu-portal {
1834
+ position: fixed;
1835
+ z-index: 2147483647;
1836
+ box-sizing: border-box;
1837
+ min-width: min(170px, calc(100vw - 16px));
1838
+ overflow: auto;
1839
+ padding: 4px;
1840
+ border: 1px solid var(--pi-border);
1841
+ border-radius: 8px;
1842
+ background: var(--pi-surface);
1843
+ color: var(--pi-text);
1844
+ box-shadow: 0 8px 24px var(--pi-shadow);
1845
+ overflow-wrap: anywhere;
1846
+ font: 14px system-ui, sans-serif;
1847
+ -webkit-touch-callout: none;
1848
+ -webkit-user-select: none;
1849
+ user-select: none;
1850
+ }
1851
+ .pi-web-app-refresh-menu-portal button {
1852
+ display: block;
1853
+ width: 100%;
1854
+ border: 0;
1855
+ border-radius: 8px;
1856
+ background: transparent;
1857
+ color: var(--pi-text);
1858
+ padding: 7px 9px;
1859
+ text-align: left;
1860
+ white-space: normal;
1861
+ overflow-wrap: anywhere;
1862
+ font: inherit;
1863
+ cursor: pointer;
1864
+ }
1865
+ .pi-web-app-refresh-menu-portal button:hover,
1866
+ .pi-web-app-refresh-menu-portal button:focus {
1867
+ background: var(--pi-selection-bg);
1868
+ }
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`
1870
+ <workspace-panel
1871
+ id="workspace-panel"
1872
+ .workspace=${e}
1873
+ .panelContext=${t}
1874
+ .emptyState=${s}
1875
+ .tool=${this.state.workspaceTool}
1876
+ .panels=${this.visibleWorkspacePanels()}
1877
+ .workspaceLabelItems=${i}
1878
+ .onSelectTool=${r=>{this.openWorkspaceTool(r)}}
1879
+ ></workspace-panel>
1880
+ `}renderNavigationPanelEdgeControl(){return l`
1881
+ <app-panel-edge-control
1882
+ side="navigation"
1883
+ controls="navigation-panel"
1884
+ expandLabel="展开导航面板"
1885
+ collapseLabel="折叠导航面板"
1886
+ .collapsed=${this.panelCollapse.navigationPanelCollapsed}
1887
+ .onToggle=${()=>{this.panelCollapse.toggleNavigationPanel()}}
1888
+ ></app-panel-edge-control>
1889
+ `}renderWorkspacePanelEdgeControl(){return l`
1890
+ <app-panel-edge-control
1891
+ side="workspace"
1892
+ controls="workspace-panel"
1893
+ expandLabel="展开工作区面板"
1894
+ collapseLabel="折叠工作区面板"
1895
+ .collapsed=${this.panelCollapse.workspacePanelCollapsed}
1896
+ .onToggle=${()=>{this.panelCollapse.toggleWorkspacePanel()}}
1897
+ ></app-panel-edge-control>
1898
+ `}renderNavigationPanel(e){const t=i=>this.withChatScrollTransition(async()=>{await i(),e&&this.setState({mainView:"chat"}),e&&this.updateUrl()});return l`
1899
+ <app-navigation-panel
1900
+ .machines=${this.state.machines}
1901
+ .selectedMachine=${this.state.selectedMachine}
1902
+ .machineStatuses=${this.state.machineStatuses}
1903
+ .machineActivities=${this.state.machineActivities}
1904
+ .machinesCollapsed=${this.mobileNavigation.isCollapsed("machines")}
1905
+ .onToggleMachines=${()=>{this.mobileNavigation.toggle("machines")}}
1906
+ .onSelectMachine=${i=>this.withChatScrollTransition(async()=>{this.mobileNavigation.expand("projects"),await this.selectMachineWithMemory(i)})}
1907
+ .onRemoveMachine=${i=>{this.removeMachine(i)}}
1908
+ .projects=${this.state.projects}
1909
+ .selectedProject=${this.state.selectedProject}
1910
+ .workspaceActivities=${this.state.workspaceActivities}
1911
+ .workspacesByProjectId=${this.state.workspacesByProjectId}
1912
+ .workspaces=${this.state.workspaces}
1913
+ .selectedWorkspace=${this.state.selectedWorkspace}
1914
+ .deletingWorkspaceIds=${_d(this.state.workspaceDeletionRuns)}
1915
+ .sessions=${this.state.sessions}
1916
+ .sessionStatuses=${this.state.sessionStatuses}
1917
+ .sessionActivities=${this.state.sessionActivities}
1918
+ .selectedSession=${this.state.selectedSession}
1919
+ .canStartSession=${!!this.state.selectedWorkspace}
1920
+ .collapsible=${this.appShell.isMobileNavigationLayout}
1921
+ .projectsCollapsed=${this.mobileNavigation.isCollapsed("projects")}
1922
+ .workspacesCollapsed=${this.mobileNavigation.isCollapsed("workspaces")}
1923
+ .sessionsCollapsed=${this.mobileNavigation.isCollapsed("sessions")}
1924
+ .workspaceLabelItems=${i=>this.plugins.getWorkspaceLabelItems(this.state,i)}
1925
+ .refreshControl=${this.appShell.shouldShowAppRefreshInHeader()?this.renderAppRefresh():void 0}
1926
+ .onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
1927
+ .onToggleProjects=${()=>{this.mobileNavigation.toggle("projects")}}
1928
+ .onToggleWorkspaces=${()=>{this.mobileNavigation.toggle("workspaces")}}
1929
+ .onToggleSessions=${()=>{this.mobileNavigation.toggle("sessions")}}
1930
+ .onSelectProject=${i=>this.withChatScrollTransition(async()=>{this.mobileNavigation.expand("workspaces"),await this.workspaces.selectProject(i)})}
1931
+ .onCloseProject=${i=>this.projects.closeProject(i.id)}
1932
+ .onSelectWorkspace=${i=>this.withChatScrollTransition(async()=>{this.mobileNavigation.expand("sessions"),await this.workspaces.selectWorkspace(i)})}
1933
+ .onDeleteWorkspace=${i=>{this.deleteWorkspace(i)}}
1934
+ .onArchivedCollapsed=${()=>{this.sessions.clearSelectionAfterArchivedCollapse()}}
1935
+ .onStartSession=${()=>t(()=>this.sessions.startSession())}
1936
+ .onSelectSession=${i=>t(()=>this.sessions.selectSession(i))}
1937
+ .onArchiveSession=${i=>this.sessions.archiveSession(i)}
1938
+ .onArchiveSessionWithDescendants=${i=>this.sessions.archiveSessionWithDescendants(i)}
1939
+ .onRestoreSession=${i=>t(()=>this.sessions.restoreSession(i))}
1940
+ .onDeleteCachedNewSession=${i=>this.sessions.deleteCachedNewSession(i)}
1941
+ .onDetachParentSession=${i=>this.sessions.detachParent(i)}
1942
+ ></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}?
1944
+
1945
+ 这会运行 git worktree remove 并删除:
1946
+ ${e.path}
1947
+
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}?
1949
+
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`
1951
+ <app-context-bar
1952
+ .machine=${this.state.selectedMachine}
1953
+ .machineActivityKind=${Gm(this.state)}
1954
+ .project=${this.state.selectedProject}
1955
+ .workspace=${this.state.selectedWorkspace}
1956
+ .session=${this.state.selectedSession}
1957
+ .refreshControl=${this.appShell.shouldShowAppRefreshInContextBar()?this.renderAppRefresh():void 0}
1958
+ .onOpenSection=${e=>{this.openNavigationSection(e)}}
1959
+ .onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
1960
+ ></app-context-bar>
1961
+ `:null}renderMobileMainTabs(){return l`
1962
+ <app-mobile-main-tabs
1963
+ .tabs=${this.mobileMainTabs()}
1964
+ .selectedView=${this.state.mainView}
1965
+ .onSelect=${e=>{this.selectMainView(e)}}
1966
+ ></app-mobile-main-tabs>
1967
+ `}mobileMainTabs(){return[{id:"navigation",label:"会话",icon:"navigation",className:"navigation-tab"},{id:"chat",label:"聊天",icon:"chat"},...this.visibleWorkspacePanels().map(e=>{const t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return l`<app-refresh-control .isRefreshing=${this.isRefreshingApp} .onRefresh=${()=>this.refreshAppData()} .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){const e=this.state;return l`
1968
+ <div class=${this.panelCollapse.shellClass(e.mainView)}>
1969
+ <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel(!1)}</aside>
1970
+ ${this.renderNavigationPanelEdgeControl()}
1971
+ <main class=${Uo(e.mainView)}>
1972
+ ${this.renderContextBar()}
1973
+ ${this.renderMobileMainTabs()}
1974
+ ${e.error?l`<div class="error">${e.error}</div>`:null}
1975
+ <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel(!0):null}</div>
1976
+ ${e.selectedSession?l`
1977
+ <chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
1978
+ <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${m(e)} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .onSend=${(t,i)=>{this.sendPrompt(t,i)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
1979
+ <status-bar .status=${e.status} .machine=${e.selectedMachine} .workspace=${e.selectedWorkspace} .workspaceLabelItems=${e.selectedWorkspace===void 0?[]:this.plugins.getWorkspaceLabelItems(e,e.selectedWorkspace)}></status-bar>
1980
+ ${e.commandDialog!==void 0?l`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??"",t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`:null}
1981
+ ${e.modelDialog!==void 0?l`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${t=>{this.pickModel(t)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`:null}
1982
+ ${e.thinkingDialog!==void 0?l`<command-picker title=${e.thinkingDialog.title} .options=${e.thinkingDialog.options} .selectedValue=${e.thinkingDialog.selectedValue} .onPick=${t=>{this.pickThinking(t)}} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`:null}
1983
+ ${e.authDialog!==void 0?l`<auth-dialog .state=${e.authDialog} .onChooseMethod=${t=>{this.auth.chooseLoginMethod(t)}} .onSelectProvider=${(t,i)=>{this.auth.selectLoginProvider(t,i)}} .onApiKeyInput=${t=>{this.auth.updateApiKey(t)}} .onSaveApiKey=${()=>{this.auth.saveApiKey()}} .onLogoutProvider=${t=>{this.auth.logoutProvider(t)}} .onOAuthInput=${t=>{this.auth.updateOAuthInput(t)}} .onOAuthRespond=${t=>{this.auth.respondOAuth(t)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`:null}
1984
+ `:l`<div class="empty">${this.sessionEmptyMessage()}</div>`}
1985
+ </main>
1986
+ ${this.renderWorkspacePanelEdgeControl()}
1987
+ ${this.renderWorkspacePanel()}
1988
+ ${e.actionPaletteOpen?l`<action-palette .actions=${this.getActions()} .onRun=${t=>{this.setState({actionPaletteOpen:!1}),this.runAction(t)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
1989
+ ${e.projectDialogOpen?l`<project-dialog .machineId=${m(e)} .onSubmit=${(t,i)=>this.projects.addProject(t,i)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
1990
+ ${e.machineDialogOpen?l`<machine-dialog .error=${e.error} .onSubmit=${t=>this.submitMachineDialog(t)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
1991
+ ${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
+ ${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
+ </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};