@jmfederico/pi-web 1.202606.0 → 1.202606.2

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 (95) hide show
  1. package/README.md +23 -7
  2. package/dist/client/assets/{CodeViewer-N88Bx8F6.js → CodeViewer-iYSv2-dg.js} +1 -1
  3. package/dist/client/assets/{TerminalPanel-DKiL51Xi.js → TerminalPanel-BpFW6j27.js} +4 -4
  4. package/dist/client/assets/index-D4dbiKXF.js +2210 -0
  5. package/dist/client/index.html +1 -1
  6. package/dist/config.js +63 -1
  7. package/dist/config.js.map +1 -1
  8. package/dist/pi-web-plugins/info/pi-web-plugin.js +8 -1
  9. package/dist/pi-web-plugins/updates/package.json +9 -0
  10. package/dist/pi-web-plugins/{pi-web → updates}/pi-web-plugin.js +38 -30
  11. package/dist/pi-web-plugins/workspace-tasks/config.js +91 -0
  12. package/dist/pi-web-plugins/workspace-tasks/package.json +9 -0
  13. package/dist/pi-web-plugins/workspace-tasks/pi-web-plugin.js +48 -0
  14. package/dist/pi-web-plugins/workspace-tasks/taskRunner.js +12 -0
  15. package/dist/pi-web-plugins/workspace-tasks/tasksPanelElement.js +292 -0
  16. package/dist/pi-web-plugins/workspace-tasks/workspaceTasksClient.js +47 -0
  17. package/dist/plugin-api/unstable.d.ts +22 -0
  18. package/dist/plugin-api.d.ts +169 -0
  19. package/dist/server/app.js +63 -26
  20. package/dist/server/app.js.map +1 -1
  21. package/dist/server/configRoutes.js +123 -0
  22. package/dist/server/configRoutes.js.map +1 -0
  23. package/dist/server/git/gitEnv.js +15 -0
  24. package/dist/server/git/gitEnv.js.map +1 -0
  25. package/dist/server/git/gitService.js +2 -1
  26. package/dist/server/git/gitService.js.map +1 -1
  27. package/dist/server/gitRoutes.js +3 -3
  28. package/dist/server/gitRoutes.js.map +1 -1
  29. package/dist/server/machines/machineClient.js +134 -0
  30. package/dist/server/machines/machineClient.js.map +1 -0
  31. package/dist/server/machines/machinePluginProxyRoutes.js +187 -0
  32. package/dist/server/machines/machinePluginProxyRoutes.js.map +1 -0
  33. package/dist/server/machines/machineProxyRoutes.js +92 -0
  34. package/dist/server/machines/machineProxyRoutes.js.map +1 -0
  35. package/dist/server/machines/machineRoutes.js +56 -0
  36. package/dist/server/machines/machineRoutes.js.map +1 -0
  37. package/dist/server/machines/machineService.js +260 -0
  38. package/dist/server/machines/machineService.js.map +1 -0
  39. package/dist/server/machines/machineStore.js +128 -0
  40. package/dist/server/machines/machineStore.js.map +1 -0
  41. package/dist/server/piWebPluginService.js +45 -15
  42. package/dist/server/piWebPluginService.js.map +1 -1
  43. package/dist/server/piWebStatus.js +127 -36
  44. package/dist/server/piWebStatus.js.map +1 -1
  45. package/dist/server/piWebStatusCache.js +32 -0
  46. package/dist/server/piWebStatusCache.js.map +1 -0
  47. package/dist/server/sessiond/sessionProxyRoutes.js +17 -14
  48. package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -1
  49. package/dist/server/sessiond.js +18 -7
  50. package/dist/server/sessiond.js.map +1 -1
  51. package/dist/server/sessions/piSessionManagerGateway.js +87 -0
  52. package/dist/server/sessions/piSessionManagerGateway.js.map +1 -0
  53. package/dist/server/sessions/piSessionService.js +147 -66
  54. package/dist/server/sessions/piSessionService.js.map +1 -1
  55. package/dist/server/sessions/sessionArchiveStore.js +12 -0
  56. package/dist/server/sessions/sessionArchiveStore.js.map +1 -1
  57. package/dist/server/sessions/sessionNameGenerator.js +2 -0
  58. package/dist/server/sessions/sessionNameGenerator.js.map +1 -1
  59. package/dist/server/sessions/sessionRoutes.js +126 -43
  60. package/dist/server/sessions/sessionRoutes.js.map +1 -1
  61. package/dist/server/terminalProxyRoutes.js +20 -10
  62. package/dist/server/terminalProxyRoutes.js.map +1 -1
  63. package/dist/server/terminals/terminalRoutes.js +11 -0
  64. package/dist/server/terminals/terminalRoutes.js.map +1 -1
  65. package/dist/server/terminals/terminalService.js +6 -0
  66. package/dist/server/terminals/terminalService.js.map +1 -1
  67. package/dist/server/workspaceExplorerRoutes.js +4 -4
  68. package/dist/server/workspaceExplorerRoutes.js.map +1 -1
  69. package/dist/server/workspaces/fileSuggestions.js +98 -17
  70. package/dist/server/workspaces/fileSuggestions.js.map +1 -1
  71. package/dist/server/workspaces/gitWorktreeDiscovery.js +3 -2
  72. package/dist/server/workspaces/gitWorktreeDiscovery.js.map +1 -1
  73. package/dist/server/workspaces/workspaceDeletionRoutes.js +113 -0
  74. package/dist/server/workspaces/workspaceDeletionRoutes.js.map +1 -0
  75. package/dist/shared/apiTypes.d.ts +498 -0
  76. package/dist/shared/apiTypes.js +3 -1
  77. package/dist/shared/apiTypes.js.map +1 -1
  78. package/dist/shared/capabilities.js +25 -0
  79. package/dist/shared/capabilities.js.map +1 -0
  80. package/dist/shared/federatedRoutes.js +61 -0
  81. package/dist/shared/federatedRoutes.js.map +1 -0
  82. package/dist/shared/machinePluginIds.js +41 -0
  83. package/dist/shared/machinePluginIds.js.map +1 -0
  84. package/dist/shared/piWebStatusParsing.js +43 -0
  85. package/dist/shared/piWebStatusParsing.js.map +1 -1
  86. package/dist/shared/pluginIds.js +5 -0
  87. package/dist/shared/pluginIds.js.map +1 -0
  88. package/dist/shared/workspaceDeletion.js +12 -0
  89. package/dist/shared/workspaceDeletion.js.map +1 -0
  90. package/docs/plugins.md +278 -71
  91. package/package.json +8 -12
  92. package/plugin-api/unstable.d.ts +1 -0
  93. package/plugin-api.d.ts +1 -148
  94. package/dist/client/assets/index-DeSR1RUE.js +0 -1446
  95. package/dist/pi-web-plugins/pi-web/package.json +0 -9
@@ -0,0 +1,2210 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-iYSv2-dg.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-BpFW6j27.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as mo,w as tt,J as Ni,R as $a,S as Pa,G as Ra,U as Ca,V as Ia,A as Ma,W as Ta,X as Aa,Y as Ea,Z as vo,x as bo,_ as Da}from"./vendor-editor-core-B4Sq6exx.js";import{m as Wa,i as _a,d as Oa}from"./vendor-editor-languages-DznYbTkJ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=i(o);fetch(o.href,r)}})();const Jt=globalThis,Ts=Jt.ShadowRoot&&(Jt.ShadyCSS===void 0||Jt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,As=Symbol(),wo=new WeakMap;let Qr=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==As)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(Ts&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=wo.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&wo.set(i,t))}return t}toString(){return this.cssText}};const La=e=>new Qr(typeof e=="string"?e:e+"",void 0,As),W=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,r)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[r+1],e[0]);return new Qr(i,e,As)},ja=(e,t)=>{if(Ts)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=Jt.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},yo=Ts?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return La(i)})(e):e;const{is:Na,defineProperty:za,getOwnPropertyDescriptor:Fa,getOwnPropertyNames:Ba,getOwnPropertySymbols:Ua,getPrototypeOf:Ha}=Object,Pi=globalThis,So=Pi.trustedTypes,qa=So?So.emptyScript:"",Ka=Pi.reactiveElementPolyfillSupport,Pt=(e,t)=>e,oi={toAttribute(e,t){switch(t){case Boolean:e=e?qa: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}},Es=(e,t)=>!Na(e,t),xo={attribute:!0,type:String,converter:oi,reflect:!1,useDefault:!1,hasChanged:Es};Symbol.metadata??=Symbol("metadata"),Pi.litPropertyMetadata??=new WeakMap;let ot=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=xo){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&za(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=Fa(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:o,set(n){const a=o?.call(this);r?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??xo}static _$Ei(){if(this.hasOwnProperty(Pt("elementProperties")))return;const t=Ha(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Pt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Pt("properties"))){const i=this.properties,s=[...Ba(i),...Ua(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const o of s)i.unshift(yo(o))}else t!==void 0&&i.push(yo(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 ja(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:oi).toAttribute(i,s.type);this._$Em=t,r==null?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const r=s.getPropertyOptions(o),n=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:oi;this._$Em=o;const a=n.fromAttribute(i,r.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,r){if(t!==void 0){const n=this.constructor;if(o===!1&&(r=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Es)(r,i)||s.useDefault&&s.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:o,wrapped:r},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),r!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:n}=r,a=this[o];n!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,r,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};ot.elementStyles=[],ot.shadowRootOptions={mode:"open"},ot[Pt("elementProperties")]=new Map,ot[Pt("finalized")]=new Map,Ka?.({ReactiveElement:ot}),(Pi.reactiveElementVersions??=[]).push("2.1.2");const Ds=globalThis,ko=e=>e,ri=Ds.trustedTypes,$o=ri?ri.createPolicy("lit-html",{createHTML:e=>e}):void 0,Zr="$lit$",ze=`lit$${Math.random().toFixed(9).slice(2)}$`,Jr="?"+ze,Va=`<${Jr}>`,Ge=document,It=()=>Ge.createComment(""),Mt=e=>e===null||typeof e!="object"&&typeof e!="function",Ws=Array.isArray,Ga=e=>Ws(e)||typeof e?.[Symbol.iterator]=="function",zi=`[
3
+ \f\r]`,ft=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Po=/-->/g,Ro=/>/g,Be=RegExp(`>|${zi}(?:([^\\s"'>=/]+)(${zi}*=${zi}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Co=/'/g,Io=/"/g,Xr=/^(?:script|style|textarea|title)$/i,Yr=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=Yr(1),rt=Yr(2),Fe=Symbol.for("lit-noChange"),L=Symbol.for("lit-nothing"),Mo=new WeakMap,Ke=Ge.createTreeWalker(Ge,129);function en(e,t){if(!Ws(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return $o!==void 0?$o.createHTML(t):t}const Qa=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=ft;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,f=0;for(;f<c.length&&(n.lastIndex=f,u=n.exec(c),u!==null);)f=n.lastIndex,n===ft?u[1]==="!--"?n=Po:u[1]!==void 0?n=Ro:u[2]!==void 0?(Xr.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=Be):u[3]!==void 0&&(n=Be):n===Be?u[0]===">"?(n=o??ft,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?Be:u[3]==='"'?Io:Co):n===Io||n===Co?n=Be:n===Po||n===Ro?n=ft:(n=Be,o=void 0);const v=n===Be&&e[a+1].startsWith("/>")?" ":"";r+=n===ft?c+Va:h>=0?(s.push(p),c.slice(0,h)+Zr+c.slice(h)+ze+v):c+ze+(h===-2?a:v)}return[en(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Tt{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=Qa(t,i);if(this.el=Tt.createElement(p,s),Ke.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Ke.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(Zr)){const f=u[n++],v=o.getAttribute(h).split(ze),P=/([.?@])?(.*)/.exec(f);c.push({type:1,index:r,name:P[2],strings:v,ctor:P[1]==="."?Ja:P[1]==="?"?Xa:P[1]==="@"?Ya:Ri}),o.removeAttribute(h)}else h.startsWith(ze)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(Xr.test(o.tagName)){const h=o.textContent.split(ze),f=h.length-1;if(f>0){o.textContent=ri?ri.emptyScript:"";for(let v=0;v<f;v++)o.append(h[v],It()),Ke.nextNode(),c.push({type:2,index:++r});o.append(h[f],It())}}}else if(o.nodeType===8)if(o.data===Jr)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(ze,h+1))!==-1;)c.push({type:7,index:r}),h+=ze.length-1}r++}}static createElement(t,i){const s=Ge.createElement("template");return s.innerHTML=t,s}}function at(e,t,i=e,s){if(t===Fe)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=Mt(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=at(e,o._$AS(e,t.values),o,s)),t}class Za{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Ge).importNode(i,!0);Ke.currentNode=o;let r=Ke.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new ct(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new el(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=Ke.nextNode(),n++)}return Ke.currentNode=Ge,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class ct{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=L,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=at(this,t,i),Mt(t)?t===L||t==null||t===""?(this._$AH!==L&&this._$AR(),this._$AH=L):t!==this._$AH&&t!==Fe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ga(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!==L&&Mt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ge.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Tt.createElement(en(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new Za(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=Mo.get(t.strings);return i===void 0&&Mo.set(t.strings,i=new Tt(t)),i}k(t){Ws(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new ct(this.O(It()),this.O(It()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=ko(t).nextSibling;ko(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Ri=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=L,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=L}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=at(this,t,i,0),n=!Mt(t)||t!==this._$AH&&t!==Fe,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=at(this,a[s+c],i,c),p===Fe&&(p=this._$AH[c]),n||=!Mt(p)||p!==this._$AH[c],p===L?t=L:t!==L&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===L?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Ja=class extends Ri{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===L?void 0:t}},Xa=class extends Ri{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==L)}},Ya=class extends Ri{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=at(this,t,i,0)??L)===Fe)return;const s=this._$AH,o=t===L&&s!==L||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==L&&(s===L||o);o&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}};class el{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){at(this,t)}}const tl={I:ct},il=Ds.litHtmlPolyfillSupport;il?.(Tt,ct),(Ds.litHtmlVersions??=[]).push("3.3.2");const sl=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new ct(t.insertBefore(It(),r),r,void 0,i??{})}return o._$AI(e),o};const _s=globalThis;let C=class extends ot{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=sl(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Fe}};C._$litElement$=!0,C.finalized=!0,_s.litElementHydrateSupport?.({LitElement:C});const ol=_s.litElementPolyfillSupport;ol?.({LitElement:C});(_s.litElementVersions??=[]).push("4.2.2");const E=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const rl={attribute:!0,type:String,converter:oi,reflect:!1,hasChanged:Es},nl=(e=rl,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const 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"?nl(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function b(e){return d({...e,state:!0,attribute:!1})}const al=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function z(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return al(i,s,{get(){return r(this)}})}}async function S(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(e,{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(ll(n)??o.statusText)}const r=await o.json();return t(r)}function ll(e){if(cl(e))return typeof e.error=="string"?e.error:void 0}function cl(e){return typeof e=="object"&&e!==null}const Os={sessionsDeleteArchived:"sessions.deleteArchived"},dl=Object.values(Os),pl=new Set(dl);function hl(e){return typeof e=="string"&&pl.has(e)}function tn(e,t){return e?.capabilities?.includes(t)===!0}function Rt(e){return typeof e=="object"&&e!==null}function y(e){if(!Rt(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function pe(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function D(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function N(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function ul(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function fl(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function gl(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:ul(t.messages),start:pe(t,"start"),total:pe(t,"total")}}function ml(e){const t=y(e);return N(sn)(t.machines)}function sn(e){const t=y(e),i=wl(t,"kind"),s=$(t,"baseUrl"),o=on(t,"status"),r=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function vl(e){const t=y(e),i=on(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:ni(t.web)},...t.sessiond===void 0?{}:{sessiond:ni(t.sessiond)},...s===void 0?{}:{error:s}}}function bl(e){const t=y(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...w("packageName",$(t,"packageName")),...w("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:an(t.components)},...t.capabilities===void 0?{}:{capabilities:Ls(t.capabilities)},...i===void 0?{}:{error:i}}}function wl(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function on(e,t){const i=$(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function To(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function yl(e){const t=y(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:D(t,"isMain"),isGitRepo:D(t,"isGitRepo"),isGitWorktree:D(t,"isGitWorktree")}}function ds(e){const t=y(e),i=$(t,"name"),s=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:pe(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function gt(e){const t=y(e);return{sessionId:m(t,"sessionId"),isStreaming:D(t,"isStreaming"),isCompacting:D(t,"isCompacting"),isBashRunning:D(t,"isBashRunning"),pendingMessageCount:pe(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:N(Sl)(t.queuedMessages),...w("messageCount",Te(t,"messageCount")),tokens:xl(t.tokens),cost:pe(t,"cost"),...kl(t.model),...Ol(t.contextUsage),...w("thinkingLevel",$(t,"thinkingLevel"))}}function Sl(e){const t=y(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text")}}function xl(e){const t=y(e);return{input:pe(t,"input"),output:pe(t,"output"),cacheRead:pe(t,"cacheRead"),cacheWrite:pe(t,"cacheWrite"),total:pe(t,"total")}}function rn(e){const t=y(e);return{...w("provider",$(t,"provider")),...w("id",$(t,"id")),...w("name",$(t,"name")),...w("contextWindow",Te(t,"contextWindow")),...w("reasoning",t.reasoning)}}function kl(e){return e===void 0?{}:{model:rn(e)}}function $l(e){const t=y(e);return{models:N(rn)(t.models)}}function Pl(e){if(e!=="off"&&e!=="minimal"&&e!=="low"&&e!=="medium"&&e!=="high"&&e!=="xhigh")throw new Error("Invalid thinking level");return e}function Rl(e){const t=y(e);return{levels:N(Pl)(t.levels)}}function Cl(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Il(e){if(e!=="stored"&&e!=="runtime"&&e!=="environment"&&e!=="fallback"&&e!=="models_json_key"&&e!=="models_json_command")throw new Error("Invalid auth status source");return e}function Ml(e){const t=y(e),i=t.source===void 0?void 0:Il(t.source);return{configured:D(t,"configured"),...w("source",i),...w("label",$(t,"label"))}}function Tl(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:Cl(t.authType),status:Ml(t.status)}}function Al(e){const t=y(e);return{providers:N(Tl)(t.providers)}}function Ft(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:El(t.status),progress:N(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...w("error",$(t,"error")),...w("auth",Dl(t.auth)),...w("prompt",Wl(t.prompt)),...w("select",_l(t.select))}}function El(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Dl(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...w("instructions",$(t,"instructions"))}}function Wl(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...w("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function _l(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:N(cn)(t.options)}}function Ol(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:Lo(t,"tokens"),contextWindow:pe(t,"contextWindow"),percent:Lo(t,"percent")}}}function Ll(e){const t=y(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...w("description",$(t,"description"))}}function nn(e){const t=y(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function jl(e){const t=y(e);return{path:m(t,"path"),entries:N(Nl)(t.entries),scannedAt:m(t,"scannedAt"),truncated:D(t,"truncated")}}function Nl(e){const t=y(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...w("size",Te(t,"size")),...w("modifiedAt",$(t,"modifiedAt"))}}function zl(e){const t=y(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...w("language",$(t,"language")),...w("mediaType",Fl(t.mediaType)),...w("mimeType",$(t,"mimeType")),encoding:i,size:pe(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:D(t,"truncated"),binary:D(t,"binary")}}function Fl(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function Bl(e){const t=y(e);return{isGitRepo:D(t,"isGitRepo"),hash:m(t,"hash"),...w("branch",$(t,"branch")),...w("upstream",$(t,"upstream")),...w("ahead",Te(t,"ahead")),...w("behind",Te(t,"behind")),files:N(Ul)(t.files)}}function Ul(e){const t=y(e);return{path:m(t,"path"),...w("oldPath",$(t,"oldPath")),index:Ao(t.index),workingTree:Ao(t.workingTree)}}function Ao(e){switch(e){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return e;default:throw new Error("Invalid git file state")}}function Hl(e){const t=y(e);return{...w("path",$(t,"path")),staged:D(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:D(t,"truncated")}}function Fi(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:D(t,"exited"),...w("exitCode",Te(t,"exitCode")),...w("commandRunId",$(t,"commandRunId"))}}function Ct(e){const t=y(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:ql(t.status),...w("exitCode",Te(t,"exitCode")),createdAt:m(t,"createdAt"),...w("startedAt",$(t,"startedAt")),...w("completedAt",$(t,"completedAt")),metadata:Kl(t.metadata,"metadata")}}function ql(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Kl(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function Vl(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:D(t,"hasSessionActivity"),hasTerminalActivity:D(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Gl(e){const t=y(e);return{workspaces:N(Vl)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Eo(e){const t=y(e);return{path:m(t,"path"),exists:D(t,"exists"),config:Do(t.config),effectiveConfig:Do(t.effectiveConfig),envOverrides:Xl(t.envOverrides)}}function Do(e){const t=y(e);return{...w("host",$(t,"host")),...w("port",Te(t,"port")),...w("allowedHosts",Ql(t.allowedHosts)),...w("shortcuts",Zl(t.shortcuts)),...w("plugins",Jl(t.plugins))}}function Ql(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 Zl(e){if(e!==void 0){if(!Rt(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 Jl(e){if(e!==void 0){if(!Rt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Rt(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!Rt(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Xl(e){const t=y(e);return{host:D(t,"host"),port:D(t,"port"),allowedHosts:D(t,"allowedHosts")}}function Yl(e){const t=y(e);return{plugins:N(ec)(t.plugins)}}function ec(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:tc(t.scope),machineSpecific:ic(t.machineSpecific,"machineSpecific")??!1,enabled:D(t,"enabled")}}function tc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function ic(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function sc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:rc(t.components),release:ac(t.release),commands:lc(t.commands),messages:N(cc)(t.messages)}}function oc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:an(t.components),capabilities:Ls(t.capabilities)}}function rc(e){const t=y(e);return{web:ni(t.web),sessiond:ni(t.sessiond)}}function an(e){const t=y(e);return{web:Wo(t.web),sessiond:Wo(t.sessiond)}}function Wo(e){const t=y(e);return{component:ln(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),available:D(t,"available"),capabilities:Ls(t.capabilities),...w("error",$(t,"error"))}}function ni(e){const t=y(e);return{component:ln(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),...w("installedVersion",$(t,"installedVersion")),stale:D(t,"stale"),available:D(t,"available"),...w("installation",nc(t.installation)),...w("error",$(t,"error"))}}function nc(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...w("path",$(t,"path")),...w("source",$(t,"source")),...s===void 0?{}:{scope:s},...w("npmRoot",$(t,"npmRoot"))}}function ac(e){const t=y(e);return{packageName:m(t,"packageName"),...w("latestVersion",$(t,"latestVersion")),updateAvailable:D(t,"updateAvailable"),...w("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...w("error",$(t,"error"))}}function lc(e){const t=y(e);return{...w("update",$(t,"update")),...w("restart",$(t,"restart")),...w("restartWeb",$(t,"restartWeb")),...w("restartSessiond",$(t,"restartSessiond")),...w("status",$(t,"status"))}}function cc(e){const t=y(e);return{id:m(t,"id"),severity:dc(t.severity),title:m(t,"title"),body:m(t,"body"),...w("command",$(t,"command"))}}function ln(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Ls(e){if(!Array.isArray(e)||!e.every(hl))throw new Error("Invalid PI WEB capabilities");return e}function dc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function _o(e){const t=y(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:N(cn)(t.options)};if(i==="done")return{type:i,...w("message",$(t,"message")),...pc(t.session),...w("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function cn(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...w("description",$(t,"description"))}}function pc(e){return e===void 0?{}:{session:ds(e)}}function Bt(e){if(y(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function ps(e){if(y(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function hc(e){if(y(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function uc(e){if(y(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Oo(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:fl(t.sessionIds,"sessionIds"),s=Te(t,"archivedCount"),o=Te(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function fc(e){if(y(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function gc(e){if(y(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function mc(e){if(y(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Te(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 Lo(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 w(e,t){return t===void 0?{}:{[e]:t}}function vc(e){return typeof e=="string"?e:e.id}function bc(e){return typeof e=="string"?void 0:e.cwd}function wc(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function yc(e,t,i="local"){const s=new URLSearchParams,o=bc(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(vc(e))}/messages${r===""?"":`?${r}`}`}function Sc(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}const M=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function xc(e){return typeof e=="string"?e:e.id}function dn(e){return typeof e=="string"?void 0:e.cwd}function pn(e,t="local"){return`${M(t)}/sessions/${encodeURIComponent(xc(e))}`}function X(e,t,i="local"){return`${pn(e,i)}/${t}`}function Ut(e,t,i="local"){return`${X(e,t,i)}${hn(e)}`}function kc(e,t="local"){return`${pn(e,t)}${hn(e)}`}function hn(e){const t=dn(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function te(e,t={}){const i=dn(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const un={piWebStatus:(e="local")=>S(e==="local"?"/api/pi-web/status":`${M(e)}/pi-web/status`,sc),piWebRuntime:()=>S("/api/pi-web/runtime",oc)},$c={machines:()=>S("/api/machines",ml),addMachine:e=>S("/api/machines",sn,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>S(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>S(`/api/machines/${encodeURIComponent(e)}/health`,vl),runtime:e=>S(`/api/machines/${encodeURIComponent(e)}/runtime`,bl)},ai={config:()=>S("/api/config",Eo),saveConfig:e=>S("/api/config",Eo,{method:"PUT",body:JSON.stringify({config:e})})},hs={plugins:()=>S("/api/plugins",Yl)},fn={workspaceActivity:(e="local")=>S(`${M(e)}/activity`,Gl)},Pc={projects:(e="local")=>S(`${M(e)}/projects`,N(To)),addProject:(e,t,i,s="local")=>S(`${M(s)}/projects`,To,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>S(`${M(t)}/projects/${encodeURIComponent(e)}`,ps,{method:"DELETE"}),projectDirectories:(e,t="local")=>S(`${M(t)}/project-directories?q=${encodeURIComponent(e)}`,N(nn))},us={workspaces:(e,t="local")=>S(`${M(t)}/projects/${e}/workspaces`,N(yl)),deleteWorkspace:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Ct,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,jl),workspaceFile:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,zl)},Rc={sessions:(e,t="local")=>S(`${M(t)}/sessions?cwd=${encodeURIComponent(e)}`,N(ds)),startSession:(e,t="local")=>S(`${M(t)}/sessions`,ds,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>S(yc(e,t,i),gl),status:(e,t="local")=>S(Ut(e,"status",t),gt),models:(e,t="local")=>S(Ut(e,"models",t),$l),setModel:(e,t,i,s="local")=>S(X(e,"model",s),gt,{method:"POST",body:te(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>S(X(e,"model/cycle",i),gt,{method:"POST",body:te(e,{direction:t})}),thinkingLevels:(e,t="local")=>S(Ut(e,"thinking-levels",t),Rl),setThinkingLevel:(e,t,i="local")=>S(X(e,"thinking-level",i),gt,{method:"POST",body:te(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>S(X(e,"thinking-level/cycle",t),gt,{method:"POST",body:te(e)}),commands:(e,t="local")=>S(Ut(e,"commands",t),N(Ll)),prompt:(e,t,i,s="local")=>S(X(e,"prompt",s),Bt,{method:"POST",body:te(e,i===void 0?{text:t}:{text:t,streamingBehavior:i})}),shell:(e,t,i="local")=>S(X(e,"shell",i),Bt,{method:"POST",body:te(e,{text:t})}),runCommand:(e,t,i="local")=>S(X(e,"commands/run",i),_o,{method:"POST",body:te(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>S(X(e,"commands/respond",s),_o,{method:"POST",body:te(e,{requestId:t,value:i})}),abort:(e,t="local")=>S(X(e,"abort",t),hc,{method:"POST",body:te(e)}),stop:(e,t="local")=>S(X(e,"stop",t),uc,{method:"POST",body:te(e)}),archive:(e,t="local")=>S(X(e,"archive",t),Oo,{method:"POST",body:te(e)}),archiveWithDescendants:(e,t="local")=>S(X(e,"archive-tree",t),Oo,{method:"POST",body:te(e)}),restore:(e,t="local")=>S(X(e,"restore",t),fc,{method:"POST",body:te(e)}),deleteArchived:(e,t="local")=>S(kc(e,t),gc,{method:"DELETE"}),detachParent:(e,t="local")=>S(X(e,"detach-parent",t),mc,{method:"POST",body:te(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return S(`${M(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Al)},saveApiKey:(e,t,i="local")=>S(`${M(i)}/auth/api-key`,Bt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>S(`${M(t)}/auth/logout`,Bt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>S(`${M(t)}/auth/oauth`,Ft,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>S(`${M(t)}/auth/oauth/${encodeURIComponent(e)}`,Ft),respondOAuthFlow:(e,t,i,s="local")=>S(`${M(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Ft,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>S(`${M(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Ft,{method:"POST"})},nt={terminals:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,N(Fi)),startTerminal:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Fi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ps,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,ps,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Fi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Ct,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>S(`${M(t)}/terminal-command-runs${Ic(e)}`,N(Ct)),getCommandRun:(e,t="local")=>Cc(e,t),cancelCommandRun:(e,t="local")=>S(`${M(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Ct,{method:"POST"})};async function Cc(e,t){const i=await fetch(`${M(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Mc(s)??i.statusText)}return Ct(await i.json())}}function Ic(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 Mc(e){if(!Tc(e))return;const t=e.error;return typeof t=="string"?t:void 0}function Tc(e){return typeof e=="object"&&e!==null}const Ac={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),S(`${M(i.machineId)}/files?${s.toString()}`,N(nn))}},Ec={gitStatus:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Bl),gitDiff:(e,t,i,s="local")=>S(wc(s,e,t,i),Hl)},O={...un,...$c,...ai,...hs,...fn,...Pc,...us,...Rc,...nt,...Ac,...Ec};function Dc(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${Ns()}${js(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function Mb(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Ns()}${js(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function Wc(e="local"){return new WebSocket(`${Ns()}${js(e)}/events`)}function js(e){return`/api/machines/${encodeURIComponent(e)}`}function Ns(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function Xt(){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 _c(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},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 Ci(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function gn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const mn="local";function Bi(e,t){return`${e}:${t}`}function vn(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??mn}class Oc{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??fn}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,Lc(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),o=g(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=jc(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function Lc(e){const t={};for(const i of e.workspaces)gn(i)&&(t[i.cwd]=i);return t}function jc(e,t){const i={...e};return gn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Nc{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??O,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=zc(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:g(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,g(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,g(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:g(this.getState())}),s=i.filter(r=>r.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,g(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",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,g(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function zc(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Dt(e){return e.replaceAll(":",".")}function Fc(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function Ui(e,t){const i=Fc(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function Se(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));Bc(o,s)}function Bc(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 jo=Dt("core:workspace.files");class Uc{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=g(this.getState()),o=await O.workspaceTree(t.id,i.id,"",s),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async n=>{r[n]=(await O.workspaceTree(t.id,i.id,n,s)).entries})),this.setState({fileTree:o.entries,expandedDirs:r,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:qc(this.getState().expandedDirs,t)});return}try{const o=await O.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),Se(jo,"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 o=await O.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(Hc(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),Se(jo,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}}function Hc(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function qc(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const No=Dt("core:workspace.git");class Kc{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 O.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Se(No,"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"}),Se(No,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,r]=await Promise.all([O.gitDiff(i.id,s.id,{path:t},g(this.getState())),O.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class Vc{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await O.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:zo(this.getState().machineActivities,o),machineRuntimes:zo(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Xt()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await O.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 O.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:Hi(this.getState().machineStatuses,t.id),machineRuntimes:Hi(this.getState().machineRuntimes,t.id),machineActivities:Hi(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await O.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await O.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(r=>r.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await O.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>O.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>O.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function Hi(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function zo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Gc{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=g(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await O.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){g(this.getState())===t&&this.setState({error:String(i)})}finally{g(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await O.addProject(t.trim(),void 0,i,g(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await O.closeProject(t,g(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 fs="pi-web:cached-new-sessions:v1",Qc="browserCachedNew",dt="local";function Wt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Fo(e,t=dt,i=Wt()){if(e.messageCount!==0||e.archived===!0)return;const s=zs(i).filter(o=>o.id!==e.id||o.machineId!==t);Fs([gs(e,t),...s],i)}function gs(e,t=dt){return{...e,browserCachedNew:!0,machineId:t}}function Bo(e,t=dt,i=Wt()){const s=zs(i).filter(o=>o.id!==e||o.machineId!==t);Fs(s,i)}function Zc(e,t,i=dt,s=Wt()){const o=new Set(t.map(c=>c.id)),r=zs(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&Fs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function ae(e){return e===void 0?!1:Yc(e)&&e.browserCachedNew===!0}function Jc(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:dt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function zs(e=Wt()){try{const t=e?.getItem(fs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Xc(s)):[]}catch{return[]}}function Fs(e,t=Wt()){try{e.length===0?t?.removeItem(fs):t?.setItem(fs,JSON.stringify(e))}catch{}}function Xc(e){if(!ed(e))return[];const t=it(e,"id"),i=it(e,"path"),s=it(e,"cwd"),o=it(e,"created"),r=it(e,"modified"),n=it(e,"firstMessage"),a=td(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=qi(e,"name"),p=qi(e,"parentSessionPath"),u=qi(e,"machineId")??dt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function Yc(e){return Qc in e}function ed(e){return typeof e=="object"&&e!==null}function it(e,t){const i=e[t];return typeof i=="string"?i:void 0}function qi(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function td(e,t){const i=e[t];return typeof i=="number"?i:void 0}function id(e){return bd(e.flatMap(Bs)).filter(t=>t.parts.length>0)}function $e(e,t){return{role:e,parts:[{type:"text",text:t}]}}function mt(e,t){const i=dd(t);return i===void 0?e:{...e,meta:i}}function sd(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,$e(t,i)]}function od(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 Bs(e){if(nd(e))return[e];if(_(e,"role")==="bashExecution")return[mt(ud(e),e)];const t=fd(_(e,"role")),i=gd(ue(e,"content"),e),s=t==="user"?ad(i):void 0;if(s!==void 0)return s.map(p=>mt(p,e));const o=cd(e);if(t==="tool")return[mt({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":t,a=r.length>0?[mt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],c=rd(e);return c===void 0?a:[...a,mt(c,e)]}function rd(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return $e("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function nd(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ue(e,"parts"))}function ad(e){if(e.length!==1||e[0]?.type!=="text")return;const t=ld(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 ld(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 cd(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function dd(e){const t=pd(ue(e,"timestamp")),i=hd(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function pd(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 hd(e){if(_(e,"role")!=="assistant")return;const t=_(e,"provider"),i=_(e,"model"),s=_(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function ud(e){const t=_(e,"command")??"",i=Yt(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ue(e,"output");s!=null&&i.push("",ci(s));const o=ue(e,"exitCode");o!=null&&i.push("",`exit ${ci(o)}`),Yt(e,"cancelled")===!0&&i.push("","cancelled"),Yt(e,"truncated")===!0&&i.push("","output truncated");const r=_(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
+ `)}]}}function fd(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function gd(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=_(i,"type"),o=_(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=_(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=_(i,"name")??"tool",n=ue(i,"arguments"),a=r==="read"?vd(_(n,"path")):void 0;if(a!==void 0)return[{type:"skillRead",...a}];const c=_(i,"id");return[{type:"toolCall",...c===void 0?{}:{toolCallId:c},toolName:r,summary:_t(n),...n===void 0?{}:{args:n}}]}return s==="image"?[{type:"text",text:"[image]"}]:Uo(i)}).map(i=>i.type==="text"&&_(t,"role")==="toolResult"?md(i.text,t):i):Uo(e)}function md(e,t){const i=_(t,"toolCallId"),s=ue(t,"content"),o=ue(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:_(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:Yt(t,"isError")===!0}}function vd(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 bd(e){const t=[],i=new Map;for(const s of e){let o=[];const r={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...r}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=wd(a),p=t.length;t.push({role:"tool",parts:[c],...r}),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&&yd(t,c,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function wd(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 yd(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=li(i.details)??o.preview,n={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...r===void 0?{}:{preview:r}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function li(e){const t=ue(e,"preview");if(!Us(t))return;const i=_(t,"diff"),s=_(t,"error"),o=xd(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function Uo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:_t(e)}]:[{type:"text",text:ci(e)}]}function _t(e){if(!Us(e))return ci(e);const t=_(e,"command");if(t!==void 0)return t;const i=_(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,r])=>r!=null).slice(0,3).map(([r,n])=>`${r}: ${Sd(n)}`).join(" · ")}function Sd(e){return typeof e=="string"?e.length>80?`${e.slice(0,77)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?"":"s"}`:typeof e=="object"&&e!==null?"object":""}function Us(e){return typeof e=="object"&&e!==null}function ue(e,t){return Us(e)?e[t]:void 0}function _(e,t){const i=ue(e,t);return typeof i=="string"?i:void 0}function Yt(e,t){const i=ue(e,t);return typeof i=="boolean"?i:void 0}function xd(e,t){const i=ue(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function ci(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const kd="pi-web:prompt-draft:";function di(e){return`${kd}${e}`}function Ii(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function bn(e,t=Ii()){try{return t?.getItem(di(e))??""}catch{return""}}function pi(e,t,i=Ii()){try{t?i?.setItem(di(e),t):i?.removeItem(di(e))}catch{}}function Hs(e,t=Ii()){try{t?.removeItem(di(e))}catch{}}function $d(e,t,i=Ii()){const s=bn(e,i);s!==""&&(pi(t,s,i),Hs(e,i))}function Pd(e,t){return $e("bash",`${t===!0?`excluded from context
6
+
7
+ `:""}$ ${e}`)}function Rd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,$e("bash",t)];const o=Id(s.text)?"":`
8
+
9
+ `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function Cd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const o=[];return!s.text.includes(`
10
+
11
+ `)&&(t.output===void 0||t.output==="")&&o.push("(no output)"),t.isError===!0&&o.push(t.output??"Bash command failed"),t.exitCode!=null&&o.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&o.push("cancelled"),t.truncated===!0&&o.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&o.push(`full output: ${t.fullOutputPath}`),o.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
+
13
+ ${o.join(`
14
+ `)}`}]}]}function Id(e){const t=e.lastIndexOf(`
15
+
16
+ `),i=e.lastIndexOf("$ ");return t>i}function Md(e,t){if(t.type==="message.append")return zd(e,t.message);if(t.type==="assistant.delta")return sd(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return od(e,t.text);if(t.type==="tool.start")return Wd(e,t);if(t.type==="tool.update")return yn(e,t.toolCallId,i=>_d(i,t));if(t.type==="tool.end")return wn(e,t.toolCallId,t.toolName,_t(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,Pd(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Rd(e,t.chunk);if(t.type==="shell.end")return Cd(e,t);if(t.type==="command.output")return[...e,$e(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,$e("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Td(e,t.message)}function Td(e,t){const i=Od(t);if(i!==void 0)return wn(e,i.toolCallId,i.toolName,_t(i.content),i.text,i.isError,i.content,i.details);const s=Bs(t);if(s.length===0)return;const o=s.map(r=>r.role==="assistant"?Ed(r):r).filter(r=>r.parts.length>0);return o.length===0?e:o.reduce((r,n)=>Ad(r,n),e)}function Ad(e,t){const i=Ld(e,t);if(i>=0)return[...e.slice(0,i),t,...e.slice(i+1)];const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||Nd(s,t)?[...e.slice(0,-1),t]:[...e,t]}function Ed(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Dd(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 Wd(e,t){const i=t.toolName==="read"?Dd(Ve(t.args,"path")):void 0;if(i!==void 0)return Fd(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 _d(e,t){const i=li(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 wn(e,t,i,s,o,r,n,a){const c=yn(e,t,h=>{const f=li(a)??h.preview;return{...h,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...f===void 0?{}:{preview:f}}});if(c!==e)return c;const p=li(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function yn(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o===void 0)continue;const r=o.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(r<0)continue;const n=o.parts[r];if(n?.type!=="toolExecution")continue;const a={...o,parts:[...o.parts.slice(0,r),i(n),...o.parts.slice(r+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function Od(e){if(Ve(e,"role")!=="toolResult")return;const t=Ve(e,"toolCallId"),i=ui(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:Ve(e,"toolName")??"tool",text:Sn(i),isError:Ud(e,"isError")===!0,content:i,details:ui(e,"details")}}function Sn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Sn).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=Ve(e,"text")??Ve(e,"content")??Ve(e,"output");if(t!==void 0)return t}return""}function Ld(e,t){const i=hi(t);if(i.length===0)return-1;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o?.role!=="skill")continue;const r=hi(o);if(xn(r,i))return s}return-1}function hi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function xn(e,t){return e.length===t.length&&e.every((i,s)=>jd(i,t[s]))}function jd(e,t){return t===void 0?!1:Ho(e.path)===Ho(t.path)||e.name===t.name}function Ho(e){return e.replace(/\\/g,"/")}function Nd(e,t){return qo(e)===qo(t)}function qo(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
+
19
+ `)}function zd(e,t){const i=Bs(t);return i.length===0?e:[...e,...i]}function Fd(e,t){const i=e.at(-1);return t.role==="skill"&&xn(hi(i),hi(t))?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Bd(e){return typeof e=="object"&&e!==null}function ui(e,t){return Bd(e)?e[t]:void 0}function Ve(e,t){const i=ui(e,t);return typeof i=="string"?i:void 0}function Ud(e,t){const i=ui(e,t);return typeof i=="boolean"?i:void 0}const Hd="pi-web:chat-history:v2:",qd=1800*1e3;function Kd(e){try{const t=sessionStorage.getItem(ms(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Jd(i))return;if(Date.now()-i.savedAt>qd){sessionStorage.removeItem(ms(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Vd(e,t){try{sessionStorage.setItem(ms(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Gd(e,t){if(e===void 0||!vs(e))return t;if(!vs(t))return e;if(Qd(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),o=new Array(s-i);return Ko(o,i,e),Ko(o,i,t),Zd(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function Qd(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Zd(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Ko(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function ms(e){return`${Hd}${e}`}function Jd(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:o}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof o=="number"&&vs({messages:t,start:i,total:s})}function vs(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(Xd)}function Xd(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 Yd={read:Kd,write:Vd};class ep{constructor(t=Yd){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return Vo(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Gd(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),Vo(s)}applyLiveEvent(t,i){return Md(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 Vo(e){const t=e?.start??0;return{messages:id(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function kn(e,t=e.length){const i=e.slice(0,t),s=ip(i,t);if(s!==void 0)return s;const o=sp(i,t);if(o!==void 0)return o;const r=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
+ `))+1,n=i.slice(r);if(i.slice(0,r).endsWith("@ "))return{kind:"file",query:n,from:r-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&r===0)return{kind:"command",query:n.slice(1),from:r,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:r,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:r,to:t,fileScope:"tracked"}}function tp(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function ip(e,t){const i=e.lastIndexOf('"');if(i===-1)return;const s=e.slice(0,i);if(s.endsWith("!@"))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"!@",quoted:!0};if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,fileScope:"tracked",quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"@ ",quoted:!0}}function sp(e,t){const i=e.lastIndexOf(`
21
+ `)+1,s=e.slice(i),o=Go(s,"@ "),r=Go(s,"!@"),n=Math.max(o,r);if(n===-1)return;const a=n===r?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function Go(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||op(e[i-1]))return i;return-1}function op(e){return e===" "||e===" "}function qs(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:np(e).startsWith("/")?{kind:"command"}:kn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function rp(e){return qs(e).kind==="shell"}function np(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
+ `))+1;return e.slice(t)}class ap{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.session=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Pn(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.session===void 0||this.session.id===""||this.session.cwd===""||!this.shouldReconnect)return;const t=Dc(this.session,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await $n(t);lp(i)&&this.onEvent?.(i)}}class Qo{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),Pn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Wc(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 $n(t);dp(i)&&this.onEvent?.(i)}}function lp(e){const t=Ks(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 cp(e){const t=Ks(e);return t==="status.update"||t==="activity.update"||t==="session.name"}function dp(e){const t=Ks(e);return cp(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Ks(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function $n(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 Pn(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function Ot(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Mi{constructor(t,i,s=Ot()){this.storageKey=t,this.parseValue=i,this.storage=s,this.values=new Map;for(const[o,r]of pp(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function Vs(e){return typeof e=="string"&&e!==""?e:void 0}function pp(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!hp(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function hp(e){return!up(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}function up(e){return typeof e=="object"&&e!==null}class fp{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}const gp="pi-web:session-selection:v1";class mp{constructor(t=Ot()){this.sessionIdsByCwd=new Mi(gp,Vs,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function vp(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return wp(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function bp(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function wp(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function yp(e,t,i){return bs(e,[t],i)}function bs(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function Sp(e,t,i){return ws(e,t,[i])}function ws(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const vt=100;class xp{constructor(t,i,s,o=new fp,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new ap,this.api=r.api??O,this.transcripts=r.transcripts??new ep}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();bp(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=g(this.getState()),s=await this.api.startSession(t.path,i);Fo(s,i);const o=gs(s,i);this.setState({sessions:[o,...this.getState().sessions]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return vp(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const h=await this.api.messages(t,{limit:vt},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const f=this.transcripts.mergeHistory(o,h);this.setState({...f,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,h=>n.push(h),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:vt},g(this.getState())),this.api.status(t,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a),u=c.isStreaming;this.catchupStreamSessionId=u?t.id:void 0,this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:u,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(ae(t)&&Ap(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i,{before:t.messagePageStart,limit:vt},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i){if(t.trim().startsWith("/"))return this.runCommand(t);if(rp(t))return this.runShell(t);const o=this.getState().selectedSession;if(!(!o||o.archived===!0))try{await this.api.prompt(o,t,i,g(this.getState())),this.markCachedNewSessionPersisted(o)}catch(r){this.setState({error:String(r)})}}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,$e("user",t)]});try{await this.api.shell(i,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,$e("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,$e("user",t)]});try{this.applyCommandResult(await this.api.runCommand(i,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,$e("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,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(ae(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,g(this.getState()));const i=this.getState(),s=yp(i.sessions,t.id,new Date().toISOString()),o=Sp(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||ae(t)))try{const i=await this.api.archiveWithDescendants(t,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=bs(o.sessions,s,new Date().toISOString()),n=ws(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=Zo(t).filter(n=>n.archived!==!0&&!ae(n));if(i.length===0)return;const s=g(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=Jo(o);if(r.length>0){const n=this.getState(),a=bs(n.sessions,r,new Date().toISOString()),c=ws(a,n.selectedSession?.id,r);this.setState({sessions:a}),c.type==="select"?await this.selectSession(c.session):c.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",o)}async deleteArchivedSessions(t){const i=Zo(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=g(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!tn(o,Os.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}const r=await Promise.allSettled(i.map(async a=>(await this.api.deleteArchived(a,s),a.id))),n=Jo(r);if(n.length>0){const a=new Set(n),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",r)}async deleteCachedNewSession(t=this.getState().selectedSession){if(!ae(t))return;this.api.stop(t,g(this.getState())).catch(()=>{}),Bo(t.id,g(this.getState())),Hs(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,g(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,g(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,g(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,g(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,g(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,t,g(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,g(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,g(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,o]=await Promise.all([this.api.messages(i,{limit:vt},g(this.getState())),this.api.status(i,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],isReceivingPartialStream:o.isStreaming}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionError(t,i){const s=$p(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return vn(g(this.getState()),t)}workspaceSelectionKey(t){return`${g(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=g(this.getState()),o=await this.api.startSession(t.cwd,s);Fo(o,s),$d(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),Bo(t.id,s);const r=gs(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!ae(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Jc(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,$e(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&pi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}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"&&!Ci(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Ip(i,t.sessionId,t.messageCount),...s?{sessionActivities:kp(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=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(Mp(t))return}if(Tp(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=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:vt},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function kp(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Zo(e){const t=new Set,i=[];for(const s of e)t.has(s.id)||(t.add(s.id),i.push(s));return i}function Jo(e){return e.filter(Pp).map(t=>t.value)}function $p(e){return e.filter(Rp).map(t=>Cp(t.reason))}function Pp(e){return e.status==="fulfilled"}function Rp(e){return e.status==="rejected"}function Cp(e){return e instanceof Error?e.message:String(e)}function Ip(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function Mp(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 Tp(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function Ap(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class Ep{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}const Dp="pi-web:workspace-selection:v1";class Wp{constructor(t=Ot()){this.workspaceIdsByProject=new Mi(Dp,Vs,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function _p(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class Op{constructor(t,i,s,o,r=new Ep,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??O}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Xt()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Bi(g(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=g(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Xt()});try{const o=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=_p(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Bi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Bi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...Xt()});try{const o=Zc(t.path,await this.api.sessions(t.path,s),s);if(g(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,g(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=jp(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function Lp(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function jp(e){return e.find(t=>t.isMain)??e[0]}const Np="pi-web:machine-navigation:v1";class zp{constructor(t=Ot()){this.snapshotsByMachine=new Mi(Np,Bp,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?er(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,er(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Fp(e){return{machineId:e,surface:{}}}function Xo(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??mn,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 Yo(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 er(e){return{...e,surface:{...e.surface}}}function Bp(e){if(!Cn(e))return;const t=We(e,"machineId");if(t===void 0)return;const i=Rn(We(e,"tool")),s=Hp(We(e,"view"));return{machineId:t,projectId:We(e,"projectId"),workspaceId:We(e,"workspaceId"),sessionId:We(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:Up(e.surface)}}function Up(e){return Cn(e)?{selectedFilePath:We(e,"selectedFilePath"),selectedDiffPath:We(e,"selectedDiffPath"),selectedTerminalId:We(e,"selectedTerminalId")}:{}}function Hp(e){return e==="navigation"||e==="chat"?e:Rn(e)}function Rn(e){return qp(e)?e:void 0}function qp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function We(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Cn(e){return typeof e=="object"&&e!==null}const Kp="pi-web:terminal-selection:v1";class Vp{constructor(t=Ot()){this.terminalIdsByCwd=new Mi(Kp,Vs,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function Tb(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function Ab(e){return e.find(t=>!t.exited)??e[0]}const In=1200,Gp=["mod","alt","shift"];class Qp{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=Tn(t);if(o===void 0)return!1;const r=Gs(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!At(o))return!1}else if(!At(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>rh(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>Qs(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},In)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Gs(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Zp(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(ys)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(Yp),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=eh(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,f=u===void 0||h?void 0:tr(u),v=h?[...a.get(p)??[]].sort(ys).map(tr):[];return{...p,active:h,shadows:v,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function Ki(e){return An(e,{requireFirstChordActivator:!0})}function Mn(e){const t=An(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ei(e){return Mn(e).map(t=>t.split("+").map(Dn).join("+")).join(" ")}function Tn(e){if(e.isComposing)return;const t=sh(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 At(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Zp(e,t,i){const s=Jp(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=Mn(o),n=r[0];if(!(n===void 0||!At(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:Xp(r),order:i}}function Jp(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Xp(e){return e.join("\0")}function tr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function ys(e,t){return ir(e.source)-ir(t.source)||sr(e.action.id,t.action.id)||sr(e.action.title,t.action.title)||e.order-t.order}function Yp(e,t){return e.tokens.length-t.tokens.length||ys(e,t)}function eh(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Qs(e.tokens,i.tokens))}function ir(e){switch(e){case"custom":return 0;case"default":return 1}}function sr(e,t){return e<t?-1:e>t?1:0}function An(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"Enter a shortcut, choose None, or reset to the default."};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=th(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!At(a.token))return{ok:!1,message:"Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured."};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function th(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"Shortcut chords must include a key."};const i=new Set;let s;for(const r of t){const n=ih(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`Shortcut has duplicate ${Dn(n)} modifiers.`};i.add(n);continue}const a=En(r);if(a===void 0)return{ok:!1,message:`Unsupported shortcut key: ${r}`};if(s!==void 0)return{ok:!1,message:"Each shortcut chord can include only one non-modifier key."};s=a}return s===void 0?{ok:!1,message:"Shortcut chords must include a key."}:{ok:!0,token:[...Gp.filter(r=>i.has(r)),s].join("+")}}function ih(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function En(e){const t=oh(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function sh(e){if(e===" ")return"space";const t=e.toLowerCase();return En(t)}function oh(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function Dn(e){return e==="mod"?or()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?or()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function rh(e,t){return e.length===t.length&&Qs(e,t)}function Qs(e,t){return t.every((i,s)=>e[s]===i)}function or(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Zs="themes:classic",nh="themes:pi-web-dark",ah={themeId:nh,auto:!0},Wn="pi-web-app-theme",lh=["--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"],ch=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function dh(){try{const e=window.localStorage.getItem(Wn);return e===null?void 0:gh(e)}catch{return}}function ph(e){try{window.localStorage.setItem(Wn,JSON.stringify(e))}catch{}}function hh(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of lh){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function uh(e){const t=fh(e.themes,e.fallbackThemeId??Zs),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=_n(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function fh(e,t=Zs){return e.find(i=>i.id===t)??e[0]}function _n(e,t){return e.find(i=>i.light===t||i.dark===t)}function gh(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return mh(i)?i:void 0}catch{return}}function mh(e){if(!vh(e))return!1;const t=e.themeId,i=e.auto;return bh(t)&&typeof i=="boolean"}function vh(e){return typeof e=="object"&&e!==null}function bh(e){return typeof e=="string"&&ch.test(e)}const wh="workspace.delete",yh="pi.operation",Sh="target.workspaceId";function xh(e){return{...e===void 0?{}:{projectId:e},metadata:{[yh]:wh}}}function kh(e){const t={};for(const i of e){const s=Ss(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function $h(e){return Object.entries(e).filter(([,t])=>fi(t)).map(([t])=>t)}function On(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&fi(i)}function Ss(e){return e.metadata[Sh]}function fi(e){return e.status==="queued"||e.status==="running"}function Ph(){return[{id:"actions.show",title:"Show Actions",description:"Open the command palette",shortcut:"mod+k",group:"General",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"Focus Prompt",description:"Move keyboard focus to the message composer",shortcut:"mod+g c",group:"General",run:e=>{e.focusPrompt()}},{id:"machine.add",title:"Add Machine",description:"Register another PI WEB runtime reachable from this gateway",group:"Machine",run:e=>e.addMachine()},{id:"machine.refresh",title:"Refresh Selected Machine",description:"Check whether the selected PI WEB runtime is online",group:"Machine",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"Open Selected Machine PI WEB",description:"Open the selected remote PI WEB directly in a new tab",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"Remove Selected Machine",description:"Remove the selected remote machine from this gateway",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"Add Project",group:"Project",run:e=>e.addProject()},{id:"auth.login",title:"Configure Provider Authentication",description:"Run /login without tying authentication to a session",group:"General",run:e=>e.configureAuth()},{id:"auth.logout",title:"Remove Provider Authentication",description:"Run /logout for stored pi credentials",group:"General",run:e=>e.logoutAuth()},{id:"theme.select",title:"Select Theme",description:"Choose the PI WEB color theme",group:"Preferences",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"Open Settings",description:"Manage PI WEB configuration and keyboard shortcuts",shortcut:"mod+,",group:"Preferences",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"Full Page Reload",description:"Reload the PI WEB browser page",group:"General",run:e=>{e.reloadPage()}},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:e=>{e.focusPrompt()}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:bt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:rr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"Go to Terminal",shortcut:"mod+4",group:"Navigation",enabled:bt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:bt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:rr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:bt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"Delete Workspace",description:"Remove the selected Git worktree",group:"Workspace",enabled:Rh,run:e=>e.deleteWorkspace()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:bt,run:e=>e.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:Ch,run:e=>e.archiveSession()},{id:"session.delete",title:"Delete New Session",description:"Delete the selected browser-cached new session",group:"Session",enabled:Ih,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&Ci(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function bt(e){return e.state.selectedWorkspace!==void 0}function rr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Rh(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!On(e.state,t)}function Ch(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ae(t)}function Ih(e){return ae(e.state.selectedSession)}const Mh="modulepreload",Th=function(e){return"/"+e},nr={},Ln=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=Th(p),p in nr)return;nr[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Mh,u||(f.as="script"),f.crossOrigin="",f.href=p,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((v,P)=>{f.addEventListener("load",v),f.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},Ah=10*1024*1024,Eh="10 MB";function Dh(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ti(e)}function ti(e){switch(e){case"navigation":return rt`
23
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
24
+ <circle cx="6" cy="7" r="1.5"></circle>
25
+ <path d="M10 7h8"></path>
26
+ <circle cx="6" cy="12" r="1.5"></circle>
27
+ <path d="M10 12h8"></path>
28
+ <circle cx="6" cy="17" r="1.5"></circle>
29
+ <path d="M10 17h8"></path>
30
+ </svg>
31
+ `;case"chat":return rt`
32
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
33
+ <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>
34
+ <path d="M8 9h8"></path>
35
+ <path d="M8 13h5"></path>
36
+ </svg>
37
+ `;case"files":return rt`
38
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
39
+ <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>
40
+ </svg>
41
+ `;case"git":return rt`
42
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
43
+ <circle cx="6" cy="6" r="2"></circle>
44
+ <circle cx="18" cy="6" r="2"></circle>
45
+ <circle cx="12" cy="18" r="2"></circle>
46
+ <path d="M8 6h6"></path>
47
+ <path d="M6 8v2a6 6 0 0 0 6 6"></path>
48
+ <path d="M18 8v2a6 6 0 0 1-6 6"></path>
49
+ </svg>
50
+ `;case"terminal":return rt`
51
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
52
+ <rect x="3" y="5" width="18" height="14" rx="2"></rect>
53
+ <path d="m7 10 3 3-3 3"></path>
54
+ <path d="M12 16h5"></path>
55
+ </svg>
56
+ `}}function Wh(){return[{id:"workspace.files",title:"Files",icon:ti("files"),order:10,render:_h},{id:"workspace.git",title:"Git",icon:ti("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:zh},{id:"workspace.terminal",title:"Terminal",icon:ti("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Nh}]}function _h(e){return l`
57
+ <section class="toolbar">
58
+ <strong>Files</strong>
59
+ ${e.fileTreeStale?l`<span class="stale">stale</span>`:null}
60
+ <button @click=${e.onRefreshFiles}>Refresh</button>
61
+ </section>
62
+ <section class="split">
63
+ <div class="list tree">
64
+ ${e.fileTree.length===0?l`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>jn(e,t,0))}
65
+ </div>
66
+ <div class="viewer">
67
+ ${Lh(e)}
68
+ </div>
69
+ </section>
70
+ `}function jn(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
71
+ <button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{Oh(e,t)}}>
72
+ <span>${t.type==="directory"?o?"▾":"▸":"·"}</span>
73
+ <span>${t.name}</span>
74
+ </button>
75
+ ${o?s.map(n=>jn(e,n,i+1)):null}
76
+ `}function Oh(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}function Lh(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">Select a file.</p>`:t===void 0?l`<p class="muted">Loading ${e.selectedFilePath}…</p>`:t.mediaType==="image"?jh(e,t):t.binary?l`<p class="muted">Binary file: ${t.path} · ${xs(t.size)}</p>`:(Nn(),l`
77
+ <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"text"}${t.truncated?" · truncated":""}</small></div>
78
+ <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
79
+ `)}function jh(e,t){const i=`${t.mimeType??"image"} · ${xs(t.size)}`;if(t.size>Ah)return l`
80
+ <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
81
+ <p class="muted">Image too large to preview: ${xs(t.size)} · limit ${Eh}</p>
82
+ `;const s=Sc(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
83
+ <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
84
+ <div class="image-preview">
85
+ <img src=${s} alt=${t.path} decoding="async" />
86
+ </div>
87
+ `}function Nh(e){return Uh(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function zh(e){const t=e.gitStatus;return l`
88
+ <section class="toolbar">
89
+ <strong>Git</strong>
90
+ ${e.gitStale?l`<span class="stale">stale</span>`:null}
91
+ <button @click=${e.onRefreshGit}>Refresh</button>
92
+ </section>
93
+ <section class="split">
94
+ <div class="list">
95
+ ${t===void 0?l`<p class="muted">No status loaded.</p>`:t.isGitRepo?l`
96
+ <p class="summary">${Hh(t)}</p>
97
+ ${t.files.length===0?l`<p class="muted">No changes.</p>`:t.files.map(i=>l`
98
+ <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
99
+ <span>${qh(i.index,i.workingTree)}</span>
100
+ <span>${i.path}</span>
101
+ </button>
102
+ `)}
103
+ `:l`<p class="muted">Not a git repository.</p>`}
104
+ </div>
105
+ <div class="viewer">
106
+ ${Fh(e)}
107
+ </div>
108
+ </section>
109
+ `}function Fh(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">Select a changed file.</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">Loading diff…</p>`;const s=[i,t].filter(o=>o.diff!=="");return s.length===0?l`<p class="muted">No staged or unstaged diff.</p>`:l`
110
+ <div class=${s.length===1?"diffs single":"diffs"}>
111
+ ${s.map(o=>Bh(o))}
112
+ </div>
113
+ `}function Bh(e){return Nn(),l`
114
+ <section class="diff-section">
115
+ <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"staged":"unstaged"}${e.truncated?" · truncated":""}</small></div>
116
+ <code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
117
+ </section>
118
+ `}function Nn(){Ln(()=>import("./CodeViewer-iYSv2-dg.js"),__vite__mapDeps([0,1,2,3]))}function Uh(){Ln(()=>import("./TerminalPanel-BpFW6j27.js"),__vite__mapDeps([4,5,6,1,2]))}function Hh(e){const t=e.branch??"detached",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function qh(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function xs(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`${Vi(t)} KB`;const i=t/1024;return i<1024?`${Vi(i)} MB`:`${Vi(i/1024)} GB`}function Vi(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const Kh={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:Ph(),workspacePanels:Wh()}})},Vh={"--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"},Gh={"--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"},Qh={"--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"},Zh={apiVersion:1,name:"PI WEB Themes",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB Dark",description:"Dark PI WEB palette.",order:10,colorScheme:"dark",tokens:Gh},{id:"pi-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:Qh},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:Vh}],themePairs:[{id:"pi-web",name:"PI WEB",description:"Follow the system light/dark preference with PI WEB themes.",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Jh=/^[a-z][a-z0-9.-]*$/u;function Xh(e){return Jh.test(e)}const Yh="machine.";function eu(e,t){if(e==="")throw new Error("Machine id is required");if(!Xh(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Yh}${tu(e)}.${t}`}function tu(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function ar(e="/pi-web-plugins/manifest.json",t={}){const i=await iu(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)if(t.shouldLoadPlugin?.(o)!==!1)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=ru(n,r);s.push({id:t.machineId===void 0?o.id:eu(t.machineId,o.id),plugin:a,machineSpecific:o.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function iu(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 su(await t.json())}}function su(e){if(!gi(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!gi(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:ou(t.machineSpecific)}})}}function ou(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function ru(e,t){if(!gi(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!nu(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function nu(e){return gi(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function gi(e){return typeof e=="object"&&e!==null}const au=/^[a-z][a-z0-9.-]*$/u,lu=/^[a-z][a-z0-9.-]*$/u,zn=new WeakMap,Fn=new WeakMap;class cu{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const o=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,o))return;this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:rt}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),o&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&o&&uu(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=gu(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=du(t,s.pluginId),r=s.enabled?.(o),n={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(o)};return s.description!==void 0&&(n.description=s.description),s.shortcut!==void 0&&(n.shortcut=s.shortcut),s.group!==void 0&&(n.group=s.group),r!==void 0&&(n.enabled=r),n})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(a?.(Gi(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(Gi(c,t)):void 0},render:c=>i.render(Gi(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,o)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,o){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(o,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!au.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!lu.test(t))throw new Error(`Invalid contribution id: ${t}`)}parseMachineSpecific(t,i){if(i===void 0)return!1;if(typeof i!="boolean")throw new Error(`Invalid plugin machineSpecific value for ${t}: ${fu(i)}`);return i}}function du(e,t){return zn.get(e)?.(t)??e}function Gi(e,t){return Fn.get(e)?.(t)??e}function pu(e,t){return zn.set(e,t),e}function hu(e,t){return Fn.set(e,t),e}function uu(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function fu(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"||typeof e=="function"||e===null||e===void 0)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function gu(e){return e.state.selectedMachine?.id??"local"}const mu=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function vu(){return typeof window>"u"||!("matchMedia"in window)?[]:mu.map(e=>window.matchMedia(e))}function lr(e,t=bu()){return e.some(i=>i.matches)||wu(t)}function bu(){return typeof navigator>"u"?void 0:navigator}function wu(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const yu=250;class Su{constructor(t=xu()){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()},yu)}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 xu(){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 ku="(max-width: 760px)";class $u{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=lr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Pu(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??vu(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Su,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=lr(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 Pu(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(ku)}const mi=["machines","projects","workspaces","sessions"];function Ru(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Js(e,t){if(e!=="none")return e??Ru(t)}function Cu(e,t){return t.isMobileLayout?Js(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Iu(e,t,i){return Js(e,i.state)===t?"none":t}function Mu(e,t,i){return i?t:e}function Tu(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Du(i)}function Au(e){return mi[mi.indexOf(e)+1]}class Eu{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Js(this.expanded,this.getState())}isCollapsed(t){return Cu(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Iu(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Tu(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Mu(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Au(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){Wu(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Du(e){const t=new Set(e);return mi.filter(i=>t.has(i))}function Wu(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class _u{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",Bn(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Bn(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const ks="pi-web:panel-sizes:v1",Ou={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Lu{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Xs(),this.panelSizes=Fu(this.storage)}hostConnected(){}constraints(t){return Lt(t)}panelWidth(t,i){return he(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=he(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=Hu(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=qu(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Bu(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${dr(he("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${dr(he("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Lt(e){return Ou[e]}function ju(e,t,i){return e==="navigation"?i-t:t-i}function Nu(e,t,i,s,o=Lt(e)){return he(e,t+ju(e,i,s),o)}function zu(e,t,i,s={}){const o=s.constraints??Lt(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=Ku(e,i,r);if(n!==void 0)return he(e,t+n,o)}function he(e,t,i=Lt(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Fu(e=Xs()){try{const t=e?.getItem(ks);if(t==null||t==="")return{};const i=JSON.parse(t);return Uu(i)}catch{return{}}}function Bu(e,t=Xs()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(ks);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=he("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=he("workspace",e.workspacePanelWidth)),t.setItem(ks,JSON.stringify(i))}catch{}}function Uu(e){if(!Vu(e)||e.version!==1)return{};const t={},i=cr(e.navigationPanelWidth),s=cr(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=he("navigation",i)),s!==void 0&&(t.workspacePanelWidth=he("workspace",s)),t}function cr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Hu(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function qu(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Ku(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function dr(e){return`${String(Math.round(e))}px`}function Xs(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Vu(e){return typeof e=="object"&&e!==null}function pr(){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:Gu(e.get("tool")),view:Qu(e.get("view"))}}function Qi(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Gu(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Un(e)?e:void 0}function Qu(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Un(e)?e:void 0}function Un(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function hr(){return Zu(new URLSearchParams(window.location.search).get("settings"))}function Zi(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function Zu(e){if(e==="general")return"general";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function Ju(e,t){return t===void 0?e:e.map(i=>Yu(i,t))}function Xu(e,t){const i=new Set(Gs(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return Ju(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?Hn(s):s)}function Yu(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Hn(e):{...e,shortcut:i}}function Hn(e){const t={...e};return delete t.shortcut,t}function ef(e,t){const i=t.api??nt,s=t.pollIntervalMs??1e3,o=t.setTimeout??sf(),r=t.clearTimeout??of();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:tf(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function tf(e,t,i,s,o){return ur(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=f=>{c||(c=!0,a!==void 0&&o(a),r(f))},u=f=>{c||(c=!0,a!==void 0&&o(a),n(f instanceof Error?f:new Error(String(f))))},h=()=>{t.getCommandRun(e.id).then(f=>{if(f!==void 0&&ur(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function ur(e){return e.status==="succeeded"||e.status==="failed"}function sf(){return(e,t)=>globalThis.setTimeout(e,t)}function of(){return e=>{globalThis.clearTimeout(e)}}function rf(e,t){return t[e.path]}function nf(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function af(e,t,i){return Kn(lf(e,t,i))}function qn(e){return Kn(Object.values(e??{}))}function Kn(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function lf(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}const Ht=0,cf=120;function jt(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Vn():df(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Ht,f=i.top-c-Ht;return[...h<cf&&f>h?[`bottom: ${st(r-i.top+Ht)};`,`max-height: ${st(Math.max(0,f))};`]:[`top: ${st(i.bottom+Ht)};`,`max-height: ${st(Math.max(0,h))};`],`right: ${st(Math.max(0,o-u))};`,`max-width: ${st(Math.max(0,u-n))};`].join(" ")}function df(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Vn()}function Vn(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function st(e){return`${String(Math.round(e))}px`}function Gn(e,t="Active"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Ti(e,t="Active"){const i=Gn(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const pf=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Qn(e){return e.composedPath().some(t=>hf(t,pf))}function hf(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 Ai(e,t){Qn(e)||t()}function Ei(e,t){return Qn(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ue(e,()=>{fr(e.currentTarget,-1)}):e.key==="ArrowDown"?Ue(e,()=>{fr(e.currentTarget,1)}):e.key==="Home"?Ue(e,()=>{gr(e.currentTarget,0)}):e.key==="End"?Ue(e,()=>{gr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ue(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ue(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ue(e,t.cancel):!1}function Di(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function Ue(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function fr(e,t){const i=Jn(e),s=Xn(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||Zn(i,o+t)}function gr(e,t){const i=Jn(e);i.length!==0&&Zn(i,t<0?i.length-1:t)}function Zn(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Jn(e){const t=Xn(e)?.getRootNode();return t===void 0||!uf(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function uf(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Xn(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const ff=W`
119
+ /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
120
+ :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; }
121
+ :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
122
+ @media (display-mode: standalone), (display-mode: fullscreen), (display-mode: minimal-ui) {
123
+ :host { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
124
+ }
125
+ .shell { --navigation-panel-size: 340px; --workspace-panel-size: minmax(360px, 42vw); --navigation-panel-width: var(--navigation-panel-size); --workspace-panel-width: var(--workspace-panel-size); display: grid; grid-template-columns: var(--navigation-panel-width) 1px minmax(320px, 1fr) 1px var(--workspace-panel-width); height: 100%; min-height: 0; }
126
+ aside { grid-column: 1; display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
127
+ aside app-navigation-panel { flex: 1 1 auto; min-height: 0; }
128
+ 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); }
129
+ .header-actions { display: flex; align-items: center; gap: 8px; }
130
+ project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
131
+ session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
132
+ main { grid-column: 3; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
133
+ .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); }
134
+ .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; }
135
+ .context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
136
+ .context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
137
+ .context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
138
+ .context-bar-label { display: none; }
139
+ .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; }
140
+ .context-bar.has-context-actions .context-items { padding-right: 52px; scroll-padding-inline: 8px 52px; }
141
+ .context-item { flex: 0 0 auto; min-width: 0; display: flex; }
142
+ .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; }
143
+ .context-actions::after { content: ""; position: absolute; top: 0; right: 0; bottom: 0; z-index: 0; width: 26px; background: var(--pi-bg); pointer-events: none; }
144
+ .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; }
145
+ .context-chip:hover { background: var(--pi-surface-hover); }
146
+ .context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
147
+ .context-chip.empty { border-style: dashed; color: var(--pi-muted); }
148
+ .context-kind { display: none; }
149
+ .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
150
+ app-mobile-main-tabs { display: none; }
151
+ .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); }
152
+ .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; }
153
+ .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
154
+ .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
155
+ .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
156
+ .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; }
157
+ .mobile-tabs button { flex: 0 0 auto; white-space: nowrap; }
158
+ .mobile-navigation-tab, .mobile-navigation-panel { display: none; }
159
+ .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
160
+ .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; }
161
+ .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; }
162
+ .navigation-panel-edge { grid-column: 2; }
163
+ .workspace-panel-edge { grid-column: 4; }
164
+ .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; }
165
+ .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; }
166
+ .shell.navigation-panel-collapsed .navigation-panel-edge-button { transform: translateX(calc(50% - .5px)); }
167
+ .shell.workspace-panel-collapsed .workspace-panel-edge-button { transform: translateX(calc(-50% + .5px)); }
168
+ .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; }
169
+ workspace-panel { grid-column: 5; min-width: 0; min-height: 0; overflow: hidden; }
170
+ @media (min-width: 1181px) {
171
+ .shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
172
+ .shell.navigation-panel-collapsed > aside { display: none; }
173
+ .shell.workspace-panel-collapsed { --workspace-panel-width: 0px; }
174
+ .shell.workspace-panel-collapsed > workspace-panel { display: none; }
175
+ }
176
+ @media (max-width: 1180px) {
177
+ .shell { grid-template-columns: var(--navigation-panel-width) 1px minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
178
+ .shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
179
+ .shell.navigation-panel-collapsed > aside { display: none; }
180
+ aside { grid-row: 1 / 3; }
181
+ .navigation-panel-edge { grid-row: 1 / 3; }
182
+ main { grid-column: 3; grid-row: 1 / 3; }
183
+ app-mobile-main-tabs { display: block; flex: 0 0 auto; min-width: 0; }
184
+ .mobile-tabs-frame { display: flex; }
185
+ .shell.workspace-view main { grid-row: 1; min-height: auto; }
186
+ .shell.workspace-view > workspace-panel { grid-column: 3; grid-row: 2; display: flex; border-left: 0; }
187
+ .shell:not(.workspace-view) > workspace-panel { display: none; }
188
+ .workspace-panel-edge { display: none; }
189
+ main.workspace-view chat-view, main.workspace-view prompt-editor, main.workspace-view status-bar,
190
+ main.workspace-view .empty { display: none; }
191
+ main.workspace-view { overflow: hidden; }
192
+ }
193
+ @media (max-width: 760px) {
194
+ .shell { grid-template-columns: minmax(0, 1fr); }
195
+ aside, .navigation-panel-edge { display: none; }
196
+ main, .shell.workspace-view > workspace-panel { grid-column: 1; }
197
+ .context-bar { display: flex; }
198
+ .mobile-navigation-tab { display: block; }
199
+ main.navigation-view chat-view, main.navigation-view prompt-editor, main.navigation-view status-bar,
200
+ main.navigation-view .empty { display: none; }
201
+ main.navigation-view .mobile-navigation-panel { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
202
+ main.navigation-view .mobile-navigation-panel app-navigation-panel { flex: 1 1 auto; min-height: 0; }
203
+ main.navigation-view .mobile-navigation-panel project-list,
204
+ main.navigation-view .mobile-navigation-panel workspace-list,
205
+ main.navigation-view .mobile-navigation-panel session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
206
+ main.navigation-view .mobile-navigation-panel project-list[collapsed],
207
+ main.navigation-view .mobile-navigation-panel workspace-list[collapsed],
208
+ main.navigation-view .mobile-navigation-panel session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
209
+ }
210
+ status-bar { flex: 0 0 auto; }
211
+ chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
212
+ prompt-editor, chat-composer { flex: 0 0 auto; }
213
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
214
+ .empty { margin: auto; color: var(--pi-muted); }
215
+ .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
216
+ `,gf=W`
217
+ :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; }
218
+ header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
219
+ .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
220
+ .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; }
221
+ .workspace-header-scroll-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
222
+ .workspace-header-scroll-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
223
+ .workspace-header-scroll-frame.can-scroll-left::before, .workspace-header-scroll-frame.can-scroll-right::after { opacity: 1; }
224
+ .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; }
225
+ .tabs { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; }
226
+ .tabs button { flex: 0 0 auto; white-space: nowrap; }
227
+ .tabs button.icon-tab { min-width: 34px; }
228
+ 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; }
229
+ button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
230
+ .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; }
231
+ .tab-custom-icon { flex: 0 0 auto; width: 16px; height: 16px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
232
+ .tab-custom-icon svg { width: 16px; height: 16px; pointer-events: none; }
233
+ .tab-label { min-width: 0; }
234
+ .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; }
235
+ @container (max-width: 430px) {
236
+ .tabs button.icon-tab { justify-content: center; padding-inline: 7px; }
237
+ .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; }
238
+ }
239
+ .panel-content { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: auto; }
240
+ .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; }
241
+ .empty-state h2 { margin: 0; color: var(--pi-text); font-size: 15px; line-height: 1.3; }
242
+ .empty-state p { margin: 0; line-height: 1.45; }
243
+ small, .muted { color: var(--pi-muted); }
244
+ @media (max-width: 1180px) { header { display: none; } }
245
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
246
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
247
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
248
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
249
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
250
+ .toolbar { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); }
251
+ .toolbar button { margin-left: auto; }
252
+ .stale { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); padding: 1px 6px; font-size: 12px; }
253
+ .split { flex: 1 1 auto; min-height: 0; display: grid; grid-template-rows: minmax(160px, 34%) minmax(0, 1fr); }
254
+ .list { min-height: 0; overflow: auto; border-bottom: 1px solid var(--pi-border); padding: 6px; }
255
+ .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); }
256
+ .row:hover, .row.selected { background: var(--pi-selection-bg); }
257
+ .row span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
258
+ .summary { margin: 4px 6px 8px; color: var(--pi-muted); }
259
+ .viewer { min-height: 0; overflow: auto; display: flex; flex-direction: column; }
260
+ .diffs { flex: 1 1 auto; min-height: 0; overflow: auto; display: grid; grid-template-rows: minmax(120px, 1fr) minmax(120px, 1fr); }
261
+ .diffs.single { grid-template-rows: minmax(0, 1fr); }
262
+ .diff-section { min-height: 0; display: flex; flex-direction: column; border-bottom: 1px solid var(--pi-border); }
263
+ .diff-section:last-child { border-bottom: 0; }
264
+ .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); }
265
+ .viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
266
+ code-viewer { flex: 1 1 auto; min-height: 0; }
267
+ .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; }
268
+ .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); }
269
+ 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; }
270
+ p { margin: 10px; }
271
+ `,Wi=W`
272
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
273
+ :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
274
+ section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
275
+ 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; }
276
+ .list-body { flex: 1 1 auto; min-height: 0; overflow: auto; }
277
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
278
+ section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
279
+ .subheading { margin-top: 14px; }
280
+ .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; }
281
+ .section-toggle span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
282
+ .section-title { display: grid; gap: 2px; min-width: 0; }
283
+ .section-toggle .section-selected { display: block; color: var(--pi-text); font-size: 12px; font-weight: 600; line-height: 1.25; text-transform: none; }
284
+ .section-toggle .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
285
+ .section-toggle small { display: inline; color: inherit; font-size: inherit; }
286
+ .action-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 6px 0; cursor: pointer; }
287
+ .action-row:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; border-radius: 8px; }
288
+ .action-row.selected .action-main, .action-row.selected .action-menu-toggle { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
289
+ .action-row.archived .action-main { color: var(--pi-muted); }
290
+ .action-main { position: relative; 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 22px 7px calc(9px + var(--depth, 0) * 16px); text-align: left; }
291
+ .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; }
292
+ .action-row:not(.selected):hover .action-main { background: var(--pi-surface-hover); }
293
+ .workspace-row .action-main { border-radius: 8px 0 0 8px; }
294
+ .workspace-primary { min-width: 0; display: flex; align-items: baseline; gap: 6px; }
295
+ .workspace-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
296
+ .workspace-status { flex: 0 0 auto; color: var(--pi-warning); font-size: 12px; }
297
+ .workspace-secondary { margin-top: 3px; }
298
+ .workspace-menu-panel { width: max-content; min-width: min(120px, calc(100vw - 16px)); padding: 8px; }
299
+ .workspace-menu-actions { margin: 0 0 8px; padding-bottom: 8px; border-bottom: 1px solid var(--pi-border-muted); }
300
+ .workspace-menu-actions button.danger { color: var(--pi-danger); }
301
+ .workspace-menu-actions button.danger:hover, .workspace-menu-actions button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
302
+ .workspace-menu-details { display: grid; gap: 6px; margin: 0; }
303
+ .workspace-detail-row { display: grid; grid-template-columns: minmax(58px, max-content) minmax(0, 1fr); gap: 8px; align-items: baseline; }
304
+ .workspace-detail-row dt { color: var(--pi-muted); font-size: 12px; white-space: normal; }
305
+ .workspace-detail-row dd { min-width: 0; margin: 0; overflow-wrap: anywhere; white-space: normal; }
306
+ .tree-marker { color: var(--pi-dim); margin-right: 5px; }
307
+ .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; }
308
+ .action-activity { position: absolute; top: 5px; right: 6px; z-index: 1; display: grid; place-items: center; width: 10px; height: 10px; }
309
+ .action-activity .activity-indicator { margin: 0; vertical-align: 0; }
310
+ .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; }
311
+ .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
312
+ .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
313
+ .action-menu { position: relative; align-self: stretch; }
314
+ .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; }
315
+ .action-menu-toggle:hover { color: var(--pi-text); background: var(--pi-surface-hover); }
316
+ .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; }
317
+ .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); }
318
+ .action-menu-panel button:hover { background: var(--pi-selection-bg); }
319
+ button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
320
+ button:disabled { opacity: .5; cursor: not-allowed; }
321
+ small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
322
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
323
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
324
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
325
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
326
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
327
+ .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
328
+ .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; }
329
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
330
+ `,mf=W`
331
+ :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; }
332
+ .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
333
+ .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
334
+ .scroll-marker { display: block; height: 0; overflow: hidden; pointer-events: none; }
335
+ .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); }
336
+ .activity-dock.active { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-bg-overlay); }
337
+ .activity-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
338
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
339
+ .activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
340
+ .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; }
341
+ .msg.user { border-color: var(--pi-accent-border); background: var(--pi-selection-bg); }
342
+ .msg.tool { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
343
+ .msg.tool-execution-shell { padding: 0; border: 0; background: transparent; color: var(--pi-text); }
344
+ .msg.system { color: var(--pi-danger); }
345
+ .msg.bash { border-color: var(--pi-success); background: var(--pi-success-bg); }
346
+ .msg.skill { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
347
+ .msg.event-group { padding: 0; border-color: var(--pi-border); background: var(--pi-bg); color: var(--pi-muted); }
348
+ .msg.event-group.live { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
349
+ .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); }
350
+ .msg.event-group.live > summary { border-bottom-color: var(--pi-success-border); background: var(--pi-success-bg); color: var(--pi-success); }
351
+ .msg.event-group > summary .label { margin: 0; }
352
+ .group-body { padding: 0 12px 12px; }
353
+ .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; }
354
+ .group-msg.tool { color: var(--pi-warning); }
355
+ .group-msg.tool-execution-shell { color: var(--pi-text); }
356
+ .group-msg.system { color: var(--pi-danger); }
357
+ .group-msg.bash { color: var(--pi-success); }
358
+ .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; }
359
+ .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; }
360
+ .history-load-button:hover, .history-load-button:focus { border-color: var(--pi-accent); color: var(--pi-text-bright); }
361
+ .history-load-button:disabled { cursor: default; opacity: .55; }
362
+ .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; }
363
+ .queued-header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
364
+ .queued-header strong { color: var(--pi-warning); }
365
+ .queued-header small { color: var(--pi-muted); }
366
+ .queued-message { display: grid; gap: 4px; padding-top: 8px; border-top: 1px solid var(--pi-border); }
367
+ .queued-message:first-of-type { padding-top: 0; border-top: 0; }
368
+ .queued-kind { color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
369
+ .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; }
370
+ .session-activity.compacting { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
371
+ .session-activity.receiving { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
372
+ .session-activity strong { color: var(--pi-purple); }
373
+ .session-activity.receiving strong { color: var(--pi-success); }
374
+ .session-activity span, .session-activity small { color: var(--pi-muted); }
375
+ .history-boundary small { color: var(--pi-dim); }
376
+ .msg-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 22px; margin-bottom: 8px; }
377
+ .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); }
378
+ .msg.user > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-accent-border) 35%, transparent); background: var(--pi-selection-bg); }
379
+ .msg.tool > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-warning-border) 35%, transparent); background: var(--pi-warning-surface); }
380
+ .msg.bash > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-success) 35%, transparent); background: var(--pi-success-bg); }
381
+ .msg.skill > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-purple-border) 35%, transparent); background: var(--pi-purple-surface); }
382
+ .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); }
383
+ .msg-header-trailing { min-width: 0; display: inline-flex; align-items: baseline; justify-content: flex-end; gap: 8px; }
384
+ .msg-actions { display: inline-flex; gap: 6px; opacity: 0; transition: opacity .12s ease; }
385
+ .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; }
386
+ .msg-action:hover, .msg-action:focus { color: var(--pi-text); border-color: var(--pi-accent); }
387
+ .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; }
388
+ .label { display: block; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
389
+ .msg-header .label { margin: 0; }
390
+ .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; }
391
+ .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; }
392
+ .msg-meta:focus { outline: 1px solid var(--pi-border); outline-offset: 3px; border-radius: 4px; }
393
+ @media (hover: none) {
394
+ .msg-actions { opacity: 1; }
395
+ .msg-meta { opacity: .75; max-width: 26px; }
396
+ .msg-meta::before { content: "ⓘ"; font-size: 13px; }
397
+ .msg-meta:focus, .msg-meta.expanded { opacity: 1; max-width: 75%; }
398
+ .msg-meta:focus::before, .msg-meta.expanded::before { content: ""; }
399
+ }
400
+ formatted-text.part { display: block; }
401
+ .part { max-width: 100%; min-width: 0; box-sizing: border-box; overflow: visible; }
402
+ .part + .part { margin-top: 10px; }
403
+ .tool-line { color: var(--pi-warning); }
404
+ .summary { color: var(--pi-muted); margin-left: 6px; }
405
+ .part:is(details) { border-top: 1px solid var(--pi-border); padding-top: 8px; }
406
+ .part > formatted-text { display: block; max-width: 100%; min-width: 0; overflow: visible; }
407
+ .skill-invocation, .skill-read { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); padding: 8px 10px; }
408
+ .skill-invocation > summary, .skill-read > strong { color: var(--pi-purple); }
409
+ .skill-invocation > small, .skill-read > small { display: block; margin: 6px 0 0; color: var(--pi-muted); }
410
+ summary { cursor: pointer; color: var(--pi-muted); }
411
+ pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
412
+ .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
413
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
414
+ `,vf=W`
415
+ :host { display: block; }
416
+ .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
417
+ p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
418
+ :is(p, ul, ol, pre, blockquote, table, .code-block-wrapper):last-child { margin-bottom: 0; }
419
+ ul, ol { padding-left: 22px; }
420
+ li + li { margin-top: 3px; }
421
+ 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; }
422
+ .code-block-wrapper { position: relative; }
423
+ .code-block-wrapper pre { margin: 0; padding-right: 40px; }
424
+ pre { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 10px; overflow-x: auto; overflow-y: hidden; }
425
+ pre code { border: 0; padding: 0; background: transparent; }
426
+ .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; }
427
+ .code-copy-button:hover, .code-copy-button:focus { color: var(--pi-text); border-color: var(--pi-accent); }
428
+ blockquote { border-left: 3px solid var(--pi-border); padding-left: 10px; color: var(--pi-muted); }
429
+ a { color: var(--pi-accent); }
430
+ h1, h2, h3, h4 { margin: 14px 0 8px; line-height: 1.2; }
431
+ h1:first-child, h2:first-child, h3:first-child, h4:first-child { margin-top: 0; }
432
+ h1 { font-size: 20px; }
433
+ h2 { font-size: 17px; }
434
+ h3 { font-size: 15px; }
435
+ h4 { font-size: 14px; }
436
+ table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
437
+ th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
438
+ th { background: var(--pi-surface); }
439
+ `,bf=W`
440
+ :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
441
+ .bar { display: flex; justify-content: flex-end; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
442
+ span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
443
+ .activity { display: inline-flex; align-items: center; gap: 6px; color: var(--pi-muted); }
444
+ .activity.active { color: var(--pi-success); }
445
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
446
+ .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
447
+ .muted { color: var(--pi-dim); }
448
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
449
+ `,wf=W`
450
+ :host { display: block; }
451
+ .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); }
452
+ 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; }
453
+ button:last-child { border-bottom: 0; }
454
+ button.selected, button:hover { background: var(--pi-selection-bg); }
455
+ span { color: var(--pi-muted); font-size: 12px; }
456
+ small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
457
+ `,Yn=W`
458
+ :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
459
+ .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
460
+ 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; }
461
+ header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
462
+ .options { min-height: 0; overflow: auto; outline: none; }
463
+ button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
464
+ header button { font-size: 20px; color: var(--pi-muted); }
465
+ 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; }
466
+ input:focus { border-color: var(--pi-accent); }
467
+ .options button { display: block; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
468
+ .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
469
+ small { display: block; margin-top: 4px; color: var(--pi-muted); }
470
+ .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
471
+ `,yf=W`
472
+ :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
473
+ .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; }
474
+ 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; }
475
+ header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid var(--pi-border); }
476
+ input { min-width: 0; border: 0; outline: none; background: transparent; color: var(--pi-text); font: 16px system-ui, sans-serif; padding: 8px; }
477
+ input::placeholder { color: var(--pi-dim); }
478
+ button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
479
+ header button { color: var(--pi-muted); font-size: 22px; padding: 2px 8px; }
480
+ .options { flex: 1 1 auto; min-height: 0; overflow: auto; }
481
+ .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; }
482
+ .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
483
+ .main { min-width: 0; }
484
+ strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
485
+ small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
486
+ .group { grid-column: 1 / -1; font-size: 12px; }
487
+ 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; }
488
+ .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
489
+ `,Sf=W`
490
+ :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
491
+ footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
492
+ footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
493
+ .editor-wrap { position: relative; min-width: 0; }
494
+ .actions { display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: nowrap; white-space: nowrap; }
495
+ .compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: var(--pi-muted); font-size: 12px; flex: 1 1 0; }
496
+ .compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
497
+ .select-model { max-width: min(42vw, 320px); }
498
+ .select-thinking { max-width: 110px; }
499
+ 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; }
500
+ textarea { overflow-y: auto; padding: 8px; }
501
+ .markdown-editor .cm-scroller { max-height: 220px; overflow-y: auto; font-family: system-ui, sans-serif; line-height: 1.4; }
502
+ .markdown-editor .cm-content { min-height: 38px; padding: 8px; caret-color: var(--pi-text); }
503
+ .markdown-editor .cm-line { padding: 0; }
504
+ .markdown-editor .cm-placeholder { color: var(--pi-dim); }
505
+ .markdown-editor .cm-focused { outline: none; }
506
+ .shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: var(--pi-success); box-shadow: 0 0 0 1px var(--pi-success-ring); }
507
+ .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; }
508
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
509
+ button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
510
+ @media (max-width: 640px) {
511
+ footer { gap: 8px; padding: 8px; }
512
+ .actions { gap: 6px; }
513
+ .compact-status { flex: 1 1 220px; gap: 4px; }
514
+ .select-model { max-width: min(58vw, 260px); }
515
+ button { padding: 6px 8px; }
516
+ }
517
+ @media (max-width: 430px) {
518
+ .compact-status { flex-basis: 170px; font-size: 11px; }
519
+ .select-model { max-width: 48vw; }
520
+ .select-thinking { max-width: 70px; }
521
+ button { padding: 5px 7px; }
522
+ }
523
+ `;var xf=Object.defineProperty,kf=Object.getOwnPropertyDescriptor,ne=(e,t,i,s)=>{for(var o=s>1?void 0:s?kf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&xf(t,i,o),o};let Q=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Di(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
524
+ <section>
525
+ <h2>${this.renderHeading()}</h2>
526
+ ${this.collapsed?null:l`
527
+ <div class="list-body">
528
+ ${this.machines.map(e=>this.renderMachine(e))}
529
+ </div>
530
+ `}
531
+ </section>
532
+ `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"online":t==="offline"?"offline":t==="error"?"error":"unknown",s=ea(e)&&this.onRemove!==void 0;return l`
533
+ <div
534
+ class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
535
+ tabindex="0"
536
+ title=${e.baseUrl??e.name}
537
+ @click=${o=>{Ai(o,()=>this.onSelect?.(e))}}
538
+ @keydown=${o=>{this.handleMachineKeydown(o,e)}}
539
+ >
540
+ <div class="action-main">
541
+ <span class="action-name machine-primary"><span class="machine-primary-label">${e.name}</span></span><small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${i}</small>
542
+ ${this.renderActivity(e)}
543
+ </div>
544
+ ${s?this.renderMachineMenu(e):null}
545
+ </div>
546
+ `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=qn(this.activities[e.id]);return Ti(i,i==="terminal"?"Machine terminal active":"Machine active")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=$f(e.id);return l`
547
+ <div class="action-menu">
548
+ <button
549
+ class="action-menu-toggle"
550
+ title="Machine actions"
551
+ aria-label=${`Actions for ${e.name}`}
552
+ aria-expanded=${String(t)}
553
+ aria-controls=${i}
554
+ @click=${s=>{s.stopPropagation(),this.toggleMenu(e.id,s.currentTarget)}}
555
+ >⋯</button>
556
+ ${t?l`
557
+ <div class="action-menu-panel machine-menu-panel" id=${i} style=${this.menuStyle} @click=${s=>{s.stopPropagation()}}>
558
+ <button class="danger" title=${`Remove ${e.name}`} @click=${()=>{this.removeMachine(e)}}>Remove</button>
559
+ </div>
560
+ `:null}
561
+ </div>
562
+ `}renderHeading(){if(!this.collapsible)return"Machines";const e=this.selected?.name??"No machine selected",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?"▸":"▾"} Machines</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=jt(t,{constrainTo:"viewport"}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}Ei(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};Q.styles=[Wi,W`
563
+ .machine-row.no-actions .action-main { border-radius: 8px; }
564
+ .machine-primary { display: flex; align-items: baseline; gap: 6px; }
565
+ .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
566
+ .machine-menu-panel button.danger { color: var(--pi-danger); }
567
+ .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
568
+ `];ne([d({attribute:!1})],Q.prototype,"machines",2);ne([d({attribute:!1})],Q.prototype,"selected",2);ne([d({attribute:!1})],Q.prototype,"statuses",2);ne([d({attribute:!1})],Q.prototype,"activities",2);ne([d({type:Boolean,reflect:!0})],Q.prototype,"collapsible",2);ne([d({type:Boolean,reflect:!0})],Q.prototype,"collapsed",2);ne([d({attribute:!1})],Q.prototype,"onSelect",2);ne([d({attribute:!1})],Q.prototype,"onRemove",2);ne([d({attribute:!1})],Q.prototype,"onToggleCollapsed",2);ne([d({attribute:!1})],Q.prototype,"onFocusNextSection",2);ne([d({attribute:!1})],Q.prototype,"onCancelKeyboardNavigation",2);ne([b()],Q.prototype,"openMenuMachineId",2);ne([b()],Q.prototype,"menuStyle",2);Q=ne([E("machine-list")],Q);function ea(e){return e.kind==="remote"}function $f(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Pf=Object.defineProperty,Rf=Object.getOwnPropertyDescriptor,ee=(e,t,i,s)=>{for(var o=s>1?void 0:s?Rf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Pf(t,i,o),o};let K=class extends C{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Di(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
569
+ <section>
570
+ <h2>${this.renderHeading()}</h2>
571
+ ${this.collapsed?null:l`
572
+ <div class="list-body">
573
+ ${this.projects.map(e=>l`
574
+ <div
575
+ class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
576
+ tabindex="0"
577
+ title=${e.path}
578
+ @click=${t=>{Ai(t,()=>this.onSelect?.(e))}}
579
+ @keydown=${t=>{this.handleProjectKeydown(t,e)}}
580
+ >
581
+ <div class="action-main">
582
+ <span class="action-name">${e.name}</span><small>${e.path}</small>
583
+ ${this.renderActivity(e)}
584
+ </div>
585
+ <div class="action-menu">
586
+ <button class="action-menu-toggle" title="Project actions" aria-label=${`Actions for ${e.name}`} @click=${t=>{t.stopPropagation(),this.toggleMenu(e.id,t.currentTarget)}}>⋯</button>
587
+ ${this.openMenuProjectId===e.id?l`
588
+ <div class="action-menu-panel" style=${this.menuStyle}>
589
+ <button title="Close project" @click=${()=>{this.close(e)}}>Close</button>
590
+ </div>
591
+ `:null}
592
+ </div>
593
+ </div>
594
+ `)}
595
+ </div>
596
+ `}
597
+ </section>
598
+ `}handleProjectKeydown(e,t){Ei(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"Projects";const e=this.selected?.name??"No project selected",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?"▸":"▾"} Projects</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=af(e,this.workspacesByProjectId[e.id]??[],this.activities);return Ti(t,t==="terminal"?"Project terminal active":"Project active")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=jt(t,{constrainTo:"viewport"}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?
599
+
600
+ This only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}};K.styles=Wi;ee([d({attribute:!1})],K.prototype,"projects",2);ee([d({attribute:!1})],K.prototype,"selected",2);ee([d({attribute:!1})],K.prototype,"activities",2);ee([d({attribute:!1})],K.prototype,"workspacesByProjectId",2);ee([d({type:Boolean,reflect:!0})],K.prototype,"collapsible",2);ee([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);ee([d({attribute:!1})],K.prototype,"onSelect",2);ee([d({attribute:!1})],K.prototype,"onClose",2);ee([d({attribute:!1})],K.prototype,"onToggleCollapsed",2);ee([d({attribute:!1})],K.prototype,"onFocusPreviousSection",2);ee([d({attribute:!1})],K.prototype,"onFocusNextSection",2);ee([d({attribute:!1})],K.prototype,"onCancelKeyboardNavigation",2);ee([b()],K.prototype,"openMenuProjectId",2);ee([b()],K.prototype,"menuStyle",2);K=ee([E("project-list")],K);function mr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Cf(t)}`)}function Cf(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&If(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 If(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Mf=Object.defineProperty,Tf=Object.getOwnPropertyDescriptor,Z=(e,t,i,s)=>{for(var o=s>1?void 0:s?Tf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Mf(t,i,o),o};let H=class extends C{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Di(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
601
+ <section>
602
+ <h2>${this.renderHeading()}</h2>
603
+ ${this.collapsed?null:l`
604
+ <div class="list-body">
605
+ ${this.workspaces.map(e=>{const t=Af(e),i=this.workspaceLabelItems(e);return l`
606
+ <div
607
+ class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
608
+ tabindex="0"
609
+ title=${t}
610
+ @click=${s=>{Ai(s,()=>this.onSelect?.(e))}}
611
+ @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
612
+ >
613
+ <div class="action-main">
614
+ ${this.renderWorkspaceMain(t,i,e)}
615
+ </div>
616
+ ${this.renderWorkspaceMenu(t,i,e)}
617
+ </div>
618
+ `})}
619
+ </div>
620
+ `}
621
+ </section>
622
+ `}renderHeading(){if(!this.collapsible)return"Workspaces";const e=this.selected===void 0?"No workspace selected":`${this.selected.label}${this.selected.isMain?" · main":""} · ${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?"▸":"▾"} Workspaces</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=nf(rf(e,this.activities));return Ti(t,t==="terminal"?"Workspace terminal active":"Workspace active")}renderWorkspaceMain(e,t,i){return l`
623
+ <span class="workspace-primary">
624
+ <span class="workspace-primary-label">${e}</span>
625
+ ${this.isDeleting(i)?l`<span class="workspace-status">Deleting…</span>`:null}
626
+ </span>
627
+ ${t.length===0?null:l`
628
+ <small class="workspace-secondary">
629
+ <span class="workspace-label">${mr(t)}</span>
630
+ </small>
631
+ `}
632
+ ${this.renderActivity(i)}
633
+ `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=Df(i.id);return l`
634
+ <div class="action-menu">
635
+ <button
636
+ class="action-menu-toggle"
637
+ title="Workspace actions and details"
638
+ aria-label=${`Actions and details for ${e}`}
639
+ aria-expanded=${String(s)}
640
+ aria-controls=${o}
641
+ @click=${r=>{r.stopPropagation(),this.toggleMenu(i.id,r.currentTarget)}}
642
+ >⋯</button>
643
+ ${s?l`
644
+ <div class="action-menu-panel workspace-menu-panel" id=${o} style=${this.menuStyle} @click=${r=>{r.stopPropagation()}}>
645
+ ${this.renderWorkspaceActions(i)}
646
+ ${this.renderWorkspaceDetails(e,t,i)}
647
+ </div>
648
+ `:null}
649
+ </div>
650
+ `}renderWorkspaceActions(e){if(!Ef(e))return;const t=this.isDeleting(e);return l`
651
+ <div class="workspace-menu-actions">
652
+ <button class="danger" title=${t?"Workspace deletion in progress":"Delete workspace"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"Deleting…":"Delete workspace"}</button>
653
+ </div>
654
+ `}renderWorkspaceDetails(e,t,i){return l`
655
+ <dl class="workspace-menu-details">
656
+ <div class="workspace-detail-row">
657
+ <dt>${i.branch===void 0?"Workspace":"Branch"}</dt>
658
+ <dd>${e}</dd>
659
+ </div>
660
+ <div class="workspace-detail-row">
661
+ <dt>Path</dt>
662
+ <dd title=${i.path}>${i.path}</dd>
663
+ </div>
664
+ ${t.length===0?null:l`
665
+ <div class="workspace-detail-row">
666
+ <dt>Details</dt>
667
+ <dd><span class="workspace-label">${mr(t)}</span></dd>
668
+ </div>
669
+ `}
670
+ </dl>
671
+ `}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=jt(t,{constrainTo:"viewport"}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}Ei(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};H.styles=Wi;Z([d({attribute:!1})],H.prototype,"workspaces",2);Z([d({attribute:!1})],H.prototype,"selected",2);Z([d({type:Boolean,reflect:!0})],H.prototype,"collapsible",2);Z([d({type:Boolean,reflect:!0})],H.prototype,"collapsed",2);Z([d({attribute:!1})],H.prototype,"workspaceLabelItems",2);Z([d({attribute:!1})],H.prototype,"activities",2);Z([d({attribute:!1})],H.prototype,"deletingWorkspaceIds",2);Z([d({attribute:!1})],H.prototype,"onSelect",2);Z([d({attribute:!1})],H.prototype,"onDelete",2);Z([d({attribute:!1})],H.prototype,"onToggleCollapsed",2);Z([d({attribute:!1})],H.prototype,"onFocusPreviousSection",2);Z([d({attribute:!1})],H.prototype,"onFocusNextSection",2);Z([d({attribute:!1})],H.prototype,"onCancelKeyboardNavigation",2);Z([b()],H.prototype,"openMenuWorkspaceId",2);Z([b()],H.prototype,"menuStyle",2);H=Z([E("workspace-list")],H);function Af(e){return`${e.branch??e.label}${e.isMain?" · main":""}`}function Ef(e){return e.isGitWorktree&&!e.isMain}function Df(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Wf=Object.defineProperty,_f=Object.getOwnPropertyDescriptor,A=(e,t,i,s)=>{for(var o=s>1?void 0:s?_f(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Wf(t,i,o),o};function wt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let I=class extends C{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.canStart=!1,this.canDeleteArchived=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions.",this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&(this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Di(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Lf(this.sessions),t=new Set(e.map(r=>r.session.id)),i=e.map(r=>r.session).filter(r=>yt(r)==="current"),s=ta(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),o=Of(this.sessions);return l`
672
+ <section>
673
+ ${this.renderHeading(e.length+s.length,i)}
674
+ ${this.collapsed?null:l`
675
+ <div class="list-body">
676
+ ${this.renderCurrentSelectionToolbar(i)}
677
+ ${e.map(r=>this.renderSession(r,o.get(r.session.id)??0,"current"))}
678
+ ${s.length>0?l`
679
+ ${this.renderArchivedHeading(s.map(r=>r.session))}
680
+ ${this.archivedExpanded?l`
681
+ ${this.renderArchivedSelectionToolbar(s.map(r=>r.session))}
682
+ ${s.map(r=>this.renderSession(r,o.get(r.session.id)??0,"archived"))}
683
+ `:null}
684
+ `:null}
685
+ </div>
686
+ `}
687
+ </section>
688
+ `}renderHeading(e,t){if(!this.collapsible)return l`
689
+ <h2>
690
+ Sessions
691
+ ${this.renderCurrentSelectionButton(t)}
692
+ <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button>
693
+ </h2>
694
+ `;const i=this.selected===void 0?"No session selected":wt(this.selected),s=this.selected?.path??i;return l`
695
+ <h2>
696
+ <button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Sessions</span>${this.collapsed?l`<small class="section-selected" title=${s}>${i}</small>`:null}</span></button>
697
+ ${this.renderCurrentSelectionButton(t)}
698
+ <small class="section-count">${e}</small>
699
+ <button ?disabled=${!this.canStart} @click=${o=>{o.stopPropagation(),this.onStart?.()}}>+</button>
700
+ </h2>
701
+ `}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;const t=this.selectionScopes.has("current");return l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"Close current session selection":"Select current sessions"} aria-label=${t?"Close current session selection":"Select current sessions"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${i=>{i.stopPropagation(),this.toggleSelection("current",e)}}>☑</button>`}renderArchivedHeading(e){const t=this.selectionScopes.has("archived");return l`
702
+ <h2 class="subheading">
703
+ <button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} Archived</span></button>
704
+ ${this.archivedExpanded?l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"Close archived session selection":"Select archived sessions"} aria-label=${t?"Close archived session selection":"Select archived sessions"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${()=>{this.toggleSelection("archived",e)}}>☑</button>`:null}
705
+ <small class="section-count">${e.length}</small>
706
+ </h2>
707
+ `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(r=>!ae(r)),s=e.length>0&&e.every(r=>this.selectedSessionIds.has(r.id)),o=e.filter(r=>this.selectedSessionIds.has(r.id)).length;return l`
708
+ <div class="bulk-row selecting">
709
+ <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!s)}}>${s?"Clear visible":"Select visible"}</button>
710
+ <small>${t.length} selected${o!==t.length?l` · ${o} visible`:null}</small>
711
+ <button ?disabled=${i.length===0} @click=${()=>{this.archiveSelectedCurrent()}}>Archive selected</button>
712
+ <button @click=${()=>{this.clearSelection("current")}}>Clear</button>
713
+ <button @click=${()=>{this.closeSelection("current")}}>Done</button>
714
+ </div>
715
+ `}renderArchivedSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("archived"))return null;const t=this.selectedSessions("archived"),i=e.length>0&&e.every(o=>this.selectedSessionIds.has(o.id)),s=e.filter(o=>this.selectedSessionIds.has(o.id)).length;return l`
716
+ <div class="bulk-row selecting">
717
+ <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!i)}}>${i?"Clear visible":"Select visible"}</button>
718
+ <small>${t.length} selected${s!==t.length?l` · ${s} visible`:null}</small>
719
+ <button class="danger" title=${this.canDeleteArchived?"Permanently delete selected archived sessions":this.archivedDeleteUnavailableMessage} ?disabled=${t.length===0||!this.canDeleteArchived} @click=${()=>{this.confirmDeleteSelectedArchived()}}>Delete selected</button>
720
+ <button @click=${()=>{this.clearSelection("archived")}}>Clear</button>
721
+ <button @click=${()=>{this.closeSelection("archived")}}>Done</button>
722
+ ${this.canDeleteArchived?null:l`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
723
+ </div>
724
+ `}renderSession(e,t,i){const{session:s}=e,o=Math.min(e.depth,2),r=yt(s)===i,n=this.selectionScopes.has(i),a=n&&r,c=a&&this.selectedSessionIds.has(s.id);return l`
725
+ <div
726
+ class="action-row ${this.selected?.id===s.id?"selected":""} ${c?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
727
+ style=${`--depth:${String(o)}`}
728
+ tabindex="0"
729
+ title=${s.path}
730
+ @click=${p=>{Ai(p,()=>{this.activateSessionRow(s,i)})}}
731
+ @keydown=${p=>{this.handleSessionKeydown(p,s,i)}}
732
+ >
733
+ <div class="action-main ${n?"selecting":""}">
734
+ ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${wt(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
735
+ <span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${wt(s)}${e.depth>2?l` <span class="badge">depth ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">parent unavailable</span>`:null}</span><small>${this.renderSessionMetaPrefix(s)}${String(s.messageCount)} messages</small>
736
+ ${this.renderActivity(s)}
737
+ </div>
738
+ <div class="action-menu">
739
+ <button class="action-menu-toggle" title="Session actions" @click=${p=>{p.stopPropagation(),this.toggleMenu(s.id,p.currentTarget)}}>⋯</button>
740
+ ${this.openMenuSessionId===s.id?l`
741
+ <div class="action-menu-panel" style=${this.menuStyle}>
742
+ ${ae(s)?l`<button title="Delete browser-cached new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(s)}}>Delete</button>`:s.archived===!0?l`
743
+ <button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(s)}}>Restore</button>
744
+ <button class="danger" title=${this.canDeleteArchived?"Permanently delete archived session":this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.openMenuSessionId=void 0,this.confirmDeleteArchived(s)}}>Delete archived session</button>
745
+ `:l`
746
+ ${s.parentSessionPath!==void 0?l`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(s)}}>Detach from parent</button>`:null}
747
+ <button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(s)}}>Archive</button>
748
+ ${t>0?l`<button title="Archive this session and its descendants" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(s,t)}}>Archive with descendants (${t})</button>`:null}
749
+ `}
750
+ </div>
751
+ `:null}
752
+ </div>
753
+ </div>
754
+ `}handleSessionKeydown(e,t,i){Ei(e,{activate:()=>{this.activateSessionRow(t,i)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&yt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){const i=t===1?"descendant session":"descendant sessions";confirm(`Archive “${wt(e)}” and ${String(t)} ${i}?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`Permanently delete archived session “${wt(e)}”? This cannot be undone.`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");if(e.length===0)return;const t=e.length===1?"archived session":"archived sessions";confirm(`Permanently delete ${String(e.length)} selected ${t}? This cannot be undone.`)&&(this.selectedSessionIds=Ji(this.selectedSessionIds,e.map(i=>i.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!ae(t));this.selectedSessionIds=Ji(this.selectedSessionIds,e.map(t=>t.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);const i=t.length===1?t[0]:void 0;i!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,i.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){const t=this.sessions.filter(i=>yt(i)===e).map(i=>i.id);this.selectedSessionIds=Ji(this.selectedSessionIds,t)}toggleSelected(e){const t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){const i=new Set(this.selectedSessionIds);for(const s of e)t?i.add(s.id):i.delete(s.id);this.selectedSessionIds=i}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&yt(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=jt(t,{constrainTo:"viewport"}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return ae(e)?"new · ":e.archived===!0?"read-only · ":""}renderActivity(e){if(!(ae(e)||e.archived===!0))return Ti(Ci(this.statuses[e.id],this.activities[e.id])?"session":void 0,"Session active")}};I.styles=[Wi,W`
755
+ h2 { min-height: 30px; }
756
+ h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
757
+ .bulk-select-entry { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; width: 30px; height: 30px; padding: 0; font-size: 13px; line-height: 1; text-transform: none; }
758
+ .bulk-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 0 0 6px; }
759
+ .bulk-row button { padding: 5px 7px; font-size: 12px; }
760
+ .bulk-row small { display: inline; min-width: 0; color: var(--pi-muted); }
761
+ .bulk-row .capability-hint { flex: 1 0 100%; color: var(--pi-warning); }
762
+ .bulk-row.selecting { padding: 6px; border: 1px solid var(--pi-border-muted); border-radius: 8px; background: color-mix(in srgb, var(--pi-surface) 65%, transparent); }
763
+ button.danger, .action-menu-panel button.danger { color: var(--pi-danger); }
764
+ button.danger:hover, .action-menu-panel button.danger:hover { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
765
+ .action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
766
+ .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
767
+ .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
768
+ `];A([d({attribute:!1})],I.prototype,"sessions",2);A([d({attribute:!1})],I.prototype,"statuses",2);A([d({attribute:!1})],I.prototype,"activities",2);A([d({attribute:!1})],I.prototype,"selected",2);A([d({type:Boolean})],I.prototype,"canStart",2);A([d({type:Boolean})],I.prototype,"canDeleteArchived",2);A([d({type:String})],I.prototype,"archivedDeleteUnavailableMessage",2);A([d({type:Boolean,reflect:!0})],I.prototype,"collapsible",2);A([d({type:Boolean,reflect:!0})],I.prototype,"collapsed",2);A([d({attribute:!1})],I.prototype,"onSelect",2);A([d({attribute:!1})],I.prototype,"onStart",2);A([d({attribute:!1})],I.prototype,"onToggleCollapsed",2);A([d({attribute:!1})],I.prototype,"onArchivedCollapsed",2);A([d({attribute:!1})],I.prototype,"onFocusPreviousSection",2);A([d({attribute:!1})],I.prototype,"onFocusNextSection",2);A([d({attribute:!1})],I.prototype,"onCancelKeyboardNavigation",2);A([d({attribute:!1})],I.prototype,"onArchive",2);A([d({attribute:!1})],I.prototype,"onArchiveWithDescendants",2);A([d({attribute:!1})],I.prototype,"onArchiveMany",2);A([d({attribute:!1})],I.prototype,"onRestore",2);A([d({attribute:!1})],I.prototype,"onDelete",2);A([d({attribute:!1})],I.prototype,"onDeleteArchived",2);A([d({attribute:!1})],I.prototype,"onDeleteArchivedMany",2);A([d({attribute:!1})],I.prototype,"onDetachParent",2);A([b()],I.prototype,"openMenuSessionId",2);A([b()],I.prototype,"menuStyle",2);A([b()],I.prototype,"archivedExpanded",2);A([b()],I.prototype,"selectionScopes",2);A([b()],I.prototype,"selectedSessionIds",2);I=A([E("session-list")],I);function yt(e){return e.archived===!0?"archived":"current"}function Ji(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Of(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Lf(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return ta(e.filter(s=>i.has(s.id)))}function ta(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 o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const Ys={CHILD:2,ELEMENT:6},eo=e=>(...t)=>({_$litDirective$:e,values:t});let to=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:jf}=tl,vr=e=>e,br=()=>document.createComment(""),St=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(br(),o),n=s.insertBefore(br(),o);i=new jf(r,n,e,e.options)}else{const r=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(r!==o||a){let c=i._$AA;for(;c!==r;){const p=vr(c).nextSibling;vr(s).insertBefore(c,o),c=p}}}return i},He=(e,t,i=e)=>(e._$AI(t,i),e),Nf={},zf=(e,t=Nf)=>e._$AH=t,Ff=e=>e._$AH,Xi=e=>{e._$AR(),e._$AA.remove()};const wr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},Bf=eo(class extends to{constructor(e){if(super(e),e.type!==Ys.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=Ff(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,f=o.length-1,v=0,P=r.length-1;for(;h<=f&&v<=P;)if(o[h]===null)h++;else if(o[f]===null)f--;else if(a[h]===n[v])c[v]=He(o[h],r[v]),h++,v++;else if(a[f]===n[P])c[P]=He(o[f],r[P]),f--,P--;else if(a[h]===n[P])c[P]=He(o[h],r[P]),St(e,c[P+1],o[h]),h++,P--;else if(a[f]===n[v])c[v]=He(o[f],r[v]),St(e,o[h],o[f]),f--,v++;else if(p===void 0&&(p=wr(n,v,P),u=wr(a,h,f)),p.has(a[h]))if(p.has(a[f])){const B=u.get(n[v]),et=B!==void 0?o[B]:null;if(et===null){const ht=St(e,o[h]);He(ht,r[v]),c[v]=ht}else c[v]=He(et,r[v]),St(e,o[h],et),o[B]=null;v++}else Xi(o[f]),f--;else Xi(o[h]),h++;for(;v<=P;){const B=St(e,c[P+1]);He(B,r[v]),c[v++]=B}for(;h<=f;){const B=o[h++];B!==null&&Xi(B)}return this.ut=n,zf(e,c),Fe}}),Uf="pi-web:chat-groups:",Hf={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(yr(e));return t===null||t===""?void 0:Kf(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(yr(e),JSON.stringify(t))}catch{}}};class qf{constructor(t=Hf){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&Sr(r,this.openGroupKeys)&&Sr(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function yr(e){return`${Uf}${e}`}function Kf(e){if(Array.isArray(e))return{open:Yi(e),closedDefaultOpen:[]};if(Vf(e))return{open:Array.isArray(e.open)?Yi(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Yi(e.closedDefaultOpen):[]}}function Yi(e){return e.filter(t=>typeof t=="string")}function Sr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Vf(e){return typeof e=="object"&&e!==null}function Gf(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(v=>xr(a,v)),u=a.parts.filter(v=>!xr(a,v)),h=t+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...f},h),p.length){n();const v=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:v,parts:p,...f},index:h})}}),n(),i}function Qf(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} history compaction ${e.length===1?"summary":"summaries"}`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} branch ${e.length===1?"summary":"summaries"}`;const t=e.reduce((s,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${s}`).join(" · ");return`${String(e.length)} ${e.length===1?"event":"events"}${i!==""?` · ${i}`:""}`}function xr(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 Zf=30;function Jf(e,t){const i=Yf(ig(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Xf(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=eg(s,t.markerOffset);return}e.scrollTop=tg(e.scrollHeight,t.distanceFromBottom)}function Yf(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function eg(e,t){return e-t}function tg(e,t){return Math.max(0,e-t)}function ig(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const sg=600,og=1;function rg(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:ng(e)||ag(e)}function ng(e){return e.scrollTop<(e.topThreshold??Math.max(sg,e.clientHeight))}function ag(e){return e.scrollHeight<=e.clientHeight+og}const lg="pi-web:chat-scroll:",cg=180,dg=48,pg=2,hg={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)}},ug={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class fg{constructor(t=hg,i=ug){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=cg){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=pg){if(t===""||i===void 0||!ts(i))return"skipped";try{if(sa(i,o)){const a={mode:"bottom"};return this.storage.setItem(es(t),JSON.stringify(a)),"saved"}const r=vg(i,s);if(r===void 0)return"skipped";const n=mg(i,r);return this.storage.setItem(es(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!ts(i))return{status:"skipped"};const r=bg(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(es(t));if(i===null||i==="")return;const s=JSON.parse(i);return gg(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!ts(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function es(e){return`${lg}${e}`}function gg(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function ts(e){return e.clientHeight>0&&e.scrollHeight>0}function ia(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function sa(e,t=dg){return ia(e)<t}function mg(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:io(t)??"",offset:t.getBoundingClientRect().top-i}}function vg(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(io(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>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function kr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function bg(e,t){return e.find(i=>io(i)===t)}function io(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var wg=Object.defineProperty,yg=Object.getOwnPropertyDescriptor,so=(e,t,i,s)=>{for(var o=s>1?void 0:s?yg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&wg(t,i,o),o};let Et=class extends C{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=$r(this.positionPercent),t=$r(this.loadedPercent),i=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return l`
769
+ <div
770
+ class="meter"
771
+ style=${`--position:${e.toFixed(2)}%;`}
772
+ role="meter"
773
+ aria-label=${i}
774
+ aria-valuemin="0"
775
+ aria-valuemax="100"
776
+ aria-valuenow=${String(Math.round(e))}
777
+ title=${i}
778
+ >
779
+ <div class="track" aria-hidden="true">
780
+ <div class="progress"></div>
781
+ <div class="marker"></div>
782
+ </div>
783
+ </div>
784
+ `}};Et.styles=W`
785
+ :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
786
+ :host(:hover), :host(:focus-within) { opacity: .92; }
787
+ .meter { height: 100%; }
788
+ .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); }
789
+ .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)); }
790
+ .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%); }
791
+ `;so([d({type:Number})],Et.prototype,"positionPercent",2);so([d({type:Number})],Et.prototype,"loadedPercent",2);Et=so([E("conversation-meter")],Et);function $r(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class $s extends to{constructor(t){if(super(t),this.it=L,t.type!==Ys.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===L||t==null)return this._t=void 0,this.it=t;if(t===Fe)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}$s.directiveName="unsafeHTML",$s.resultType=1;const Sg=eo($s);function oo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Je=oo();function oa(e){Je=e}var qe={exec:()=>null};function R(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(o,r)=>{let n=typeof r=="string"?r:r.source;return n=n.replace(G.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var xg=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),G={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)}}>`)},kg=/^(?:[ \t]*(?:\n|$))+/,$g=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Pg=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Nt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Rg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ro=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ra=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,na=R(ra).replace(/bull/g,ro).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(),Cg=R(ra).replace(/bull/g,ro).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(),no=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ig=/^[^\n]+/,ao=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Mg=R(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ao).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Tg=R(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,ro).getRegex(),_i="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",lo=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ag=R("^ {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",lo).replace("tag",_i).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),aa=R(no).replace("hr",Nt).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",_i).getRegex(),Eg=R(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",aa).getRegex(),co={blockquote:Eg,code:$g,def:Mg,fences:Pg,heading:Rg,hr:Nt,html:Ag,lheading:na,list:Tg,newline:kg,paragraph:aa,table:qe,text:Ig},Pr=R("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Nt).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",_i).getRegex(),Dg={...co,lheading:Cg,table:Pr,paragraph:R(no).replace("hr",Nt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Pr).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",_i).getRegex()},Wg={...co,html:R(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",lo).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:qe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:R(no).replace("hr",Nt).replace("heading",` *#{1,6} *[^
792
+ ]`).replace("lheading",na).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},_g=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Og=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,la=/^( {2,}|\\)\n(?!\s*$)/,Lg=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,pt=/[\p{P}\p{S}]/u,Oi=/[\s\p{P}\p{S}]/u,po=/[^\s\p{P}\p{S}]/u,jg=R(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Oi).getRegex(),ca=/(?!~)[\p{P}\p{S}]/u,Ng=/(?!~)[\s\p{P}\p{S}]/u,zg=/(?:[^\s\p{P}\p{S}]|~)/u,Fg=R(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",xg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),da=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Bg=R(da,"u").replace(/punct/g,pt).getRegex(),Ug=R(da,"u").replace(/punct/g,ca).getRegex(),pa="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Hg=R(pa,"gu").replace(/notPunctSpace/g,po).replace(/punctSpace/g,Oi).replace(/punct/g,pt).getRegex(),qg=R(pa,"gu").replace(/notPunctSpace/g,zg).replace(/punctSpace/g,Ng).replace(/punct/g,ca).getRegex(),Kg=R("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,po).replace(/punctSpace/g,Oi).replace(/punct/g,pt).getRegex(),Vg=R(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,pt).getRegex(),Gg="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Qg=R(Gg,"gu").replace(/notPunctSpace/g,po).replace(/punctSpace/g,Oi).replace(/punct/g,pt).getRegex(),Zg=R(/\\(punct)/,"gu").replace(/punct/g,pt).getRegex(),Jg=R(/^<(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(),Xg=R(lo).replace("(?:-->|$)","-->").getRegex(),Yg=R("^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",Xg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),vi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,em=R(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",vi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ha=R(/^!?\[(label)\]\[(ref)\]/).replace("label",vi).replace("ref",ao).getRegex(),ua=R(/^!?\[(ref)\](?:\[\])?/).replace("ref",ao).getRegex(),tm=R("reflink|nolink(?!\\()","g").replace("reflink",ha).replace("nolink",ua).getRegex(),Rr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ho={_backpedal:qe,anyPunctuation:Zg,autolink:Jg,blockSkip:Fg,br:la,code:Og,del:qe,delLDelim:qe,delRDelim:qe,emStrongLDelim:Bg,emStrongRDelimAst:Hg,emStrongRDelimUnd:Kg,escape:_g,link:em,nolink:ua,punctuation:jg,reflink:ha,reflinkSearch:tm,tag:Yg,text:Lg,url:qe},im={...ho,link:R(/^!?\[(label)\]\((.*?)\)/).replace("label",vi).getRegex(),reflink:R(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",vi).getRegex()},Ps={...ho,emStrongRDelimAst:qg,emStrongLDelim:Ug,delLDelim:Vg,delRDelim:Qg,url:R(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Rr).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:R(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Rr).getRegex()},sm={...Ps,br:R(la).replace("{2,}","*").getRegex(),text:R(Ps.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},qt={normal:co,gfm:Dg,pedantic:Wg},xt={normal:ho,gfm:Ps,breaks:sm,pedantic:im},om={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Cr=e=>om[e];function Me(e,t){if(t){if(G.escapeTest.test(e))return e.replace(G.escapeReplace,Cr)}else if(G.escapeTestNoEncode.test(e))return e.replace(G.escapeReplaceNoEncode,Cr);return e}function Ir(e){try{e=encodeURI(e).replace(G.percentDecode,"%")}catch{return null}return e}function Mr(e,t){let i=e.replace(G.findPipe,(r,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(G.splitPipe),o=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;o<s.length;o++)s[o]=s[o].trim().replace(G.slashPipe,"|");return s}function Ne(e,t,i){let s=e.length;if(s===0)return"";let o=0;for(;o<s&&e.charAt(s-o-1)===t;)o++;return e.slice(0,s-o)}function Tr(e){let t=e.split(`
793
+ `),i=t.length-1;for(;i>=0&&G.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
794
+ `)}function rm(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 nm(e,t=0){let i=t,s="";for(let o of e)if(o===" "){let r=4-i%4;s+=" ".repeat(r),i+=r}else s+=o,i++;return s}function Ar(e,t,i,s,o){let r=t.href,n=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:r,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function am(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
795
+ `).map(r=>{let n=r.match(i.other.beginningSpace);if(n===null)return r;let[a]=n;return a.length>=o.length?r.slice(o.length):r}).join(`
796
+ `)}var bi=class{options;rules;lexer;constructor(e){this.options=e||Je}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]:Tr(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=am(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let s=Ne(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Ne(t[0],`
797
+ `),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Ne(t[0],`
798
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Ne(t[0],`
799
+ `).split(`
800
+ `),s="",o="",r=[];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(`
801
+ `),u=p.replace(this.rules.other.blockquoteSetextReplace,`
802
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
803
+ ${p}`:p,o=o?`${o}
804
+ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=h,i.length===0)break;let f=r.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let v=f,P=v.raw+`
805
+ `+i.join(`
806
+ `),B=this.blockquote(P);r[r.length-1]=B,s=s.substring(0,s.length-v.raw.length)+B.raw,o=o.substring(0,o.length-v.text.length)+B.text;break}else if(f?.type==="list"){let v=f,P=v.raw+`
807
+ `+i.join(`
808
+ `),B=this.list(P);r[r.length-1]=B,s=s.substring(0,s.length-f.raw.length)+B.raw,o=o.substring(0,o.length-v.raw.length)+B.raw,i=P.substring(r.at(-1).raw.length).split(`
809
+ `);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=nm(t[2].split(`
810
+ `,1)[0],t[1].length),f=e.split(`
811
+ `,1)[0],v=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):v?P=t[1].length+1:(P=h.search(this.rules.other.nonSpaceChar),P=P>4?1:P,u=h.slice(P),P+=t[1].length),v&&this.rules.other.blankLine.test(f)&&(p+=f+`
812
+ `,e=e.substring(f.length+1),c=!0),!c){let B=this.rules.other.nextBulletRegex(P),et=this.rules.other.hrRegex(P),ht=this.rules.other.fencesBeginRegex(P),go=this.rules.other.headingBeginRegex(P),xa=this.rules.other.htmlBeginRegex(P),ka=this.rules.other.blockquoteBeginRegex(P);for(;e;){let ji=e.split(`
813
+ `,1)[0],ut;if(f=ji,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),ut=f):ut=f.replace(this.rules.other.tabCharGlobal," "),ht.test(f)||go.test(f)||xa.test(f)||ka.test(f)||B.test(f)||et.test(f))break;if(ut.search(this.rules.other.nonSpaceChar)>=P||!f.trim())u+=`
814
+ `+ut.slice(P);else{if(v||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ht.test(h)||go.test(h)||et.test(h))break;u+=`
815
+ `+f}v=!f.trim(),p+=ji+`
816
+ `,e=e.substring(ji.length+1),h=ut.slice(P)}}o.loose||(n?o.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),o.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=p}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let c of o.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,o.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(!o.loose){let u=c.tokens.filter(f=>f.type==="space"),h=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));o.loose=h}}if(o.loose)for(let c of o.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Tr(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Ne(t[0],`
817
+ `),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Mr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
818
+ `):[],r={type:"table",raw:Ne(t[0],`
819
+ `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(Mr(n,r.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Ne(t[0],`
820
+ `),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)===`
821
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let r=Ne(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=rm(t[2],"()");if(r===-2)return;if(r>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],o=r[3])}else o=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),Ar(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[s.toLowerCase()];if(!o){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return Ar(i,o,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(n=[...r].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&o%3&&!((o+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,o+s.index+u+n);if(Math.min(o,n)%2){let v=h.slice(1,-1);return{type:"em",raw:h,text:v,tokens:this.lexer.inlineTokens(v)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),o=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&o&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+o);(s=c.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r||(n=[...r].length,n!==o))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,o+s.index+p+n),h=u.slice(o,-o);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},xe=class Rs{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Je,this.options.tokenizer=this.options.tokenizer||new bi,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:G,block:qt.normal,inline:xt.normal};this.options.pedantic?(i.block=qt.pedantic,i.inline=xt.pedantic):this.options.gfm&&(i.block=qt.gfm,this.options.breaks?i.inline=xt.breaks:i.inline=xt.gfm),this.tokenizer.rules=i}static get rules(){return{block:qt,inline:xt}}static lex(t,i){return new Rs(i).lex(t)}static lexInline(t,i){return new Rs(i).inlineTokens(t)}lex(t){t=t.replace(G.carriageReturn,`
822
+ `),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(G.tabCharGlobal," ").replace(G.spaceLine,""));let o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(a=>(r=a.call({lexer:this},t,i))?(t=t.substring(r.raw.length),i.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let a=i.at(-1);r.raw.length===1&&a!==void 0?a.raw+=`
823
+ `:i.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
824
+ `)?"":`
825
+ `)+r.raw,a.text+=`
826
+ `+r.text,this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(r=this.tokenizer.fences(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.heading(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.hr(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.blockquote(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.list(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.html(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.def(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
827
+ `)?"":`
828
+ `)+r.raw,a.text+=`
829
+ `+r.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},i.push(r));continue}if(r=this.tokenizer.table(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.lheading(t)){t=t.substring(r.raw.length),i.push(r);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,c=t.slice(1),p;this.options.extensions.startBlock.forEach(u=>{p=u.call({lexer:this},c),typeof p=="number"&&p>=0&&(a=Math.min(a,p))}),a<1/0&&a>=0&&(n=t.substring(0,a+1))}if(this.state.top&&(r=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
830
+ `)?"":`
831
+ `)+r.raw,a.text+=`
832
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r),s=n.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
833
+ `)?"":`
834
+ `)+r.raw,a.text+=`
835
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,f=t.slice(1),v;this.options.extensions.startInline.forEach(P=>{v=P.call({lexer:this},f),typeof v=="number"&&v>=0&&(h=Math.min(h,v))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},wi=class{options;parser;constructor(e){this.options=e||Je}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(G.notSpaceStart)?.[0],o=e.replace(G.endingNewline,"")+`
836
+ `;return s?'<pre><code class="language-'+Me(s)+'">'+(i?o:Me(o,!0))+`</code></pre>
837
+ `:"<pre><code>"+(i?o:Me(o,!0))+`</code></pre>
838
+ `}blockquote({tokens:e}){return`<blockquote>
839
+ ${this.parser.parse(e)}</blockquote>
840
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
841
+ `}hr(e){return`<hr>
842
+ `}list(e){let t=e.ordered,i=e.start,s="";for(let n=0;n<e.items.length;n++){let a=e.items[n];s+=this.listitem(a)}let o=t?"ol":"ul",r=t&&i!==1?' start="'+i+'"':"";return"<"+o+r+`>
843
+ `+s+"</"+o+`>
844
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
845
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
846
+ `}table(e){let t="",i="";for(let o=0;o<e.header.length;o++)i+=this.tablecell(e.header[o]);t+=this.tablerow({text:i});let s="";for(let o=0;o<e.rows.length;o++){let r=e.rows[o];i="";for(let n=0;n<r.length;n++)i+=this.tablecell(r[n]);s+=this.tablerow({text:i})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
847
+ <thead>
848
+ `+t+`</thead>
849
+ `+s+`</table>
850
+ `}tablerow({text:e}){return`<tr>
851
+ ${e}</tr>
852
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
853
+ `}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>${Me(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),o=Ir(e);if(o===null)return s;e=o;let r='<a href="'+e+'"';return t&&(r+=' title="'+Me(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let o=Ir(e);if(o===null)return Me(i);e=o;let r=`<img src="${e}" alt="${Me(i)}"`;return t&&(r+=` title="${Me(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Me(e.text)}},uo=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}},ke=class Cs{options;renderer;textRenderer;constructor(t){this.options=t||Je,this.options.renderer=this.options.renderer||new wi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new uo}static parse(t,i){return new Cs(i).parse(t)}static parseInline(t,i){return new Cs(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let n=o,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let r=o;switch(r.type){case"space":{i+=this.renderer.space(r);break}case"hr":{i+=this.renderer.hr(r);break}case"heading":{i+=this.renderer.heading(r);break}case"code":{i+=this.renderer.code(r);break}case"table":{i+=this.renderer.table(r);break}case"blockquote":{i+=this.renderer.blockquote(r);break}case"list":{i+=this.renderer.list(r);break}case"checkbox":{i+=this.renderer.checkbox(r);break}case"html":{i+=this.renderer.html(r);break}case"def":{i+=this.renderer.def(r);break}case"paragraph":{i+=this.renderer.paragraph(r);break}case"text":{i+=this.renderer.text(r);break}default:{let n='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=a||"";continue}}let n=r;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},$t=class{options;block;constructor(e){this.options=e||Je}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?xe.lex:xe.lexInline}provideParser(e=this.block){return e?ke.parse:ke.parseInline}},lm=class{defaults=oo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ke;Renderer=wi;TextRenderer=uo;Lexer=xe;Tokenizer=bi;Hooks=$t;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let o=s;for(let r of o.header)i=i.concat(this.walkTokens(r.tokens,t));for(let r of o.rows)for(let n of r)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let o=s;i=i.concat(this.walkTokens(o.items,t));break}default:{let o=s;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let n=o[r].flat(1/0);i=i.concat(this.walkTokens(n,t))}):o.tokens&&(i=i.concat(this.walkTokens(o.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=t.renderers[o.name];r?t.renderers[o.name]=function(...n){let a=o.renderer.apply(this,n);return a===!1&&(a=r.apply(this,n)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[o.level];r?r.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),s.extensions=t),i.renderer){let o=this.defaults.renderer||new wi(this.defaults);for(let r in i.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let n=r,a=i.renderer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u||""}}s.renderer=o}if(i.tokenizer){let o=this.defaults.tokenizer||new bi(this.defaults);for(let r in i.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let n=r,a=i.tokenizer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.tokenizer=o}if(i.hooks){let o=this.defaults.hooks||new $t;for(let r in i.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let n=r,a=i.hooks[n],c=o[n];$t.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&$t.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await a.call(o,p);return c.call(o,h)})();let u=a.call(o,p);return c.call(o,u)}:o[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(o,p);return h===!1&&(h=await c.apply(o,p)),h})();let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.hooks=o}if(i.walkTokens){let o=this.defaults.walkTokens,r=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(r.call(this,n)),o&&(a=a.concat(o.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return xe.lex(e,t??this.defaults)}parser(e,t){return ke.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},o={...this.defaults,...s},r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let n=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?xe.lex:xe.lexInline)(n,o),c=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?ke.parse:ke.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(r);try{o.hooks&&(t=o.hooks.preprocess(t));let n=(o.hooks?o.hooks.provideLexer(e):e?xe.lex:xe.lexInline)(t,o);o.hooks&&(n=o.hooks.processAllTokens(n)),o.walkTokens&&this.walkTokens(n,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?ke.parse:ke.parseInline)(n,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(n){return r(n)}}}onError(e,t){return i=>{if(i.message+=`
854
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Me(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},Qe=new lm;function T(e,t){return Qe.parse(e,t)}T.options=T.setOptions=function(e){return Qe.setOptions(e),T.defaults=Qe.defaults,oa(T.defaults),T};T.getDefaults=oo;T.defaults=Je;T.use=function(...e){return Qe.use(...e),T.defaults=Qe.defaults,oa(T.defaults),T};T.walkTokens=function(e,t){return Qe.walkTokens(e,t)};T.parseInline=Qe.parseInline;T.Parser=ke;T.parser=ke.parse;T.Renderer=wi;T.TextRenderer=uo;T.Lexer=xe;T.lexer=xe.lex;T.Tokenizer=bi;T.Hooks=$t;T.parse=T;T.options;T.setOptions;T.use;T.walkTokens;T.parseInline;ke.parse;xe.lex;const fa=new T.Renderer;fa.html=({text:e})=>pm(e);const cm=300,kt=new Map;function dm(e){const t=kt.get(e);if(t!==void 0)return t;const i=T.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:fa}),s=hm(i);if(kt.set(e,s),kt.size>cm){const o=kt.keys().next().value;o!==void 0&&kt.delete(o)}return s}function pm(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function hm(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const o=s.name.toLowerCase();o.startsWith("on")&&i.removeAttribute(s.name),(o==="href"||o==="src")&&!um(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function um(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var fm=Object.defineProperty,gm=Object.getOwnPropertyDescriptor,ga=(e,t,i,s)=>{for(var o=s>1?void 0:s?gm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&fm(t,i,o),o};let yi=class extends C{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)}}render(){return l`<div class="formatted" @click=${this.onFormattedClick}>${Sg(dm(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="Copy code block",s.setAttribute("aria-label","Copy code block");const o=document.createElement("span");o.setAttribute("aria-hidden","true"),o.textContent="⧉",s.append(o),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await mm(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"?"Copied code block":t==="failed"?"Failed to copy code block":"Copy code block";e.title=s,e.setAttribute("aria-label",s)}};yi.styles=vf;ga([d()],yi.prototype,"text",2);yi=ga([E("formatted-text")],yi);async function mm(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var vm=Object.defineProperty,bm=Object.getOwnPropertyDescriptor,zt=(e,t,i,s)=>{for(var o=s>1?void 0:s?bm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&vm(t,i,o),o};const Er=180;let Ze=class extends C{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=wm(e.args),s=ym(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:Sm(r),a=s!==void 0&&o?.diff!==void 0&&s!==o.diff,c=e.status==="error"?e.resultText:o?.error,p=r===void 0?e.resultText:void 0;return l`
855
+ <section class=${`tool-card ${e.status}`}>
856
+ <div class="tool-header">
857
+ <div class="tool-title">
858
+ <span class="status-icon" aria-hidden="true">${km(e.status)}</span>
859
+ <strong>${e.toolName}</strong>
860
+ ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
861
+ </div>
862
+ <div class="tool-meta">
863
+ ${Dr(e)===void 0?null:l`<span>${Dr(e)}</span>`}
864
+ ${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
865
+ <span class="status-label">${$m(e.status)}</span>
866
+ </div>
867
+ </div>
868
+
869
+ ${a?l`<p class="notice">Applied diff differs from the preview.</p>`:null}
870
+ ${c===void 0||c===""?null:l`<pre class="error-text">${c}</pre>`}
871
+ ${r===void 0?this.renderTextBody(p,e.status==="error"):this.renderDiffBody(r,s===void 0?"Preview diff":"Applied diff")}
872
+ ${!t&&r===void 0&&(p===void 0||p==="")?l`<p class="muted">${e.summary}</p>`:null}
873
+ </section>
874
+ `}renderTextBody(e,t){return e===void 0||e===""?null:l`
875
+ <details class="text-body" ?open=${t}>
876
+ <summary>Result</summary>
877
+ <pre>${e}</pre>
878
+ </details>
879
+ `}renderDiffBody(e,t){const i=e.split(`
880
+ `),s=!this.showFullDiff&&i.length>Er,o=s?i.slice(0,Er):i;return l`
881
+ <details class="diff-details" ?open=${this.diffOpen} @toggle=${r=>{this.onDiffToggle(r)}}>
882
+ <summary>
883
+ <span>${t}</span>
884
+ <small>${String(i.length)} ${i.length===1?"line":"lines"}</small>
885
+ </summary>
886
+ <div class="diff-toolbar">
887
+ <span>${s?`Showing ${String(o.length)} of ${String(i.length)} lines`:"Full diff"}</span>
888
+ <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"Copied":"Copy diff"}</button>
889
+ </div>
890
+ <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${xm(r)}>${r}</span>`)}</code></pre>
891
+ ${s?l`
892
+ <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
893
+ Show all ${String(i.length)} diff lines
894
+ </button>
895
+ `:null}
896
+ </details>
897
+ `}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}}};Ze.styles=W`
898
+ :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
899
+ .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); }
900
+ .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
901
+ .tool-card.success { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
902
+ .tool-card.error { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); }
903
+ .tool-header { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; min-width: 0; }
904
+ .tool-title { display: inline-flex; align-items: baseline; gap: 7px; min-width: 0; }
905
+ .status-icon { flex: 0 0 auto; color: var(--pi-muted); }
906
+ strong { color: var(--pi-text); }
907
+ .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; }
908
+ .summary { color: var(--pi-muted); font-family: inherit; }
909
+ .tool-meta { flex: 0 0 auto; display: inline-flex; align-items: baseline; gap: 8px; color: var(--pi-muted); font-size: 12px; }
910
+ .diff-stats { display: inline-flex; gap: 3px; }
911
+ .added, .diff .added { color: var(--pi-success); }
912
+ .removed, .diff .removed { color: var(--pi-danger); }
913
+ .status-label { text-transform: uppercase; letter-spacing: .04em; color: var(--pi-muted); }
914
+ .notice { margin: 0; color: var(--pi-warning); }
915
+ .muted { margin: 0; color: var(--pi-muted); }
916
+ .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; }
917
+ .text-body { border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
918
+ .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); }
919
+ .diff-details { min-width: 0; max-width: 100%; border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
920
+ .diff-details > summary { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; min-width: 0; color: var(--pi-muted); cursor: pointer; }
921
+ .diff-details > summary span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
922
+ .diff-details > summary small { flex: 0 0 auto; color: var(--pi-dim); }
923
+ .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; }
924
+ .diff-toolbar span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
925
+ 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; }
926
+ button:hover, button:focus { border-color: var(--pi-accent); }
927
+ .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; }
928
+ .diff-content { display: block; width: max-content; min-width: 100%; }
929
+ .diff span { display: block; min-height: 1.45em; padding: 0 8px; white-space: pre; }
930
+ .diff .context { color: var(--pi-muted); }
931
+ .diff .hunk { color: var(--pi-accent); }
932
+ .diff .file { color: var(--pi-dim); }
933
+ .diff .meta { color: var(--pi-dim); }
934
+ .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
935
+ .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
936
+ .show-more { justify-self: start; }
937
+ `;zt([d({attribute:!1})],Ze.prototype,"execution",2);zt([b()],Ze.prototype,"showFullDiff",2);zt([b()],Ze.prototype,"copied",2);zt([b()],Ze.prototype,"diffOpen",2);Ze=zt([E("tool-execution-view")],Ze);function wm(e){return Is(e,"path")??Is(e,"file_path")}function Dr(e){if(e.toolName!=="edit")return;const t=ii(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?"":"s"}`;if(typeof ii(e.args,"oldText")=="string"&&typeof ii(e.args,"newText")=="string")return"1 edit"}function ym(e){return Is(e,"diff")}function Sm(e){let t=0,i=0;for(const s of e.split(`
938
+ `))ma(s)?t++:va(s)&&i++;return{added:t,removed:i}}function xm(e){return ma(e)?"added":va(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function ma(e){return e.startsWith("+")&&!e.startsWith("+++")}function va(e){return e.startsWith("-")&&!e.startsWith("---")}function km(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function $m(e){return e==="success"?"done":e==="error"?"failed":e==="running"?"running":"pending"}function Pm(e){return typeof e=="object"&&e!==null}function ii(e,t){return Pm(e)?e[t]:void 0}function Is(e,t){const i=ii(e,t);return typeof i=="string"?i:void 0}var Rm=Object.defineProperty,Cm=Object.getOwnPropertyDescriptor,F=(e,t,i,s)=>{for(var o=s>1?void 0:s?Cm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Rm(t,i,o),o};const Im=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Mm=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),is=["You opened this chat while the assistant was already replying. The complete answer will appear shortly.","We joined mid-sentence. Holding the curtain until the full reply is ready.","The assistant started before this tab arrived. We’ll show the full answer when it lands.","Catching the reply in one piece — no spoilers, no half-answers.","The tokens are still assembling themselves. Full answer incoming.","We arrived fashionably late to this response. The complete version will appear soon."];function Wr(){return is[Math.floor(Math.random()*is.length)]??is[0]}function _r(e){return si(e,0,100)}function si(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let j=class extends C{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 qf,this.scrollController=new fg,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`
939
+ <div class="chat-wrap">
940
+ ${this.renderConversationRail()}
941
+ <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
942
+ ${this.renderHistoryBoundary()}
943
+ ${Bf(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)))}
944
+ ${this.renderQueuedMessages()}
945
+ ${this.renderSessionActivity()}
946
+ </div>
947
+ ${this.renderActivityDock()}
948
+ </div>
949
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Gf(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`
950
+ <div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
951
+ <span class="dot"></span>
952
+ <span class="activity-text">${this.activityText(e)}</span>
953
+ </div>
954
+ `}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return e.length===0?null:l`
955
+ <aside class="queued-messages" aria-live="polite">
956
+ <div class="queued-header">
957
+ <strong>Queued messages</strong>
958
+ <small>${e.length} pending · Stop clears the queue</small>
959
+ </div>
960
+ ${e.map((t,i)=>l`
961
+ <div class="queued-message">
962
+ <span class="queued-kind">${t.kind==="steer"?"Steer":"Follow-up"} ${String(i+1)}</span>
963
+ <formatted-text .text=${t.text}></formatted-text>
964
+ </div>
965
+ `)}
966
+ </aside>
967
+ `}renderSessionActivity(){return this.isReceivingPartialStream?l`
968
+ <aside class="session-activity receiving" aria-live="polite">
969
+ <strong>Catching up…</strong>
970
+ <span>${this.currentPartialStreamNoticeBody()}</span>
971
+ </aside>
972
+ `:this.isCompacting?l`
973
+ <aside class="session-activity compacting" aria-live="polite">
974
+ <strong>Compacting history…</strong>
975
+ <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
976
+ ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?"message":"messages"}</small>`:null}
977
+ </aside>
978
+ `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Wr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Wr(),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!=="idle"&&t.phase==="idle"?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?_r(this.messages.length/e*100):100;return l`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=si(this.currentConversationIndex??t,0,e-1);return _r(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?l`
979
+ <div class="history-boundary">
980
+ <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
981
+ <span>Scroll up to load earlier messages</span>
982
+ ${e}
983
+ </div>
984
+ `:this.messages.length?l`<div class="history-boundary"><span>Beginning of session</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>Showing messages ${e}–${t} of ${i}</small>`}loadedRawMessageEnd(){return Math.max(this.messageEnd,this.messageStart+this.messages.length)}renderMessage(e,t){const i=this.isToolExecutionOnlyMessage(e);return l`
985
+ ${this.renderScrollMarker(this.messageScrollMarkerId(t))}
986
+ <article class=${i?"msg tool-execution-shell":`msg ${e.role}`} data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
987
+ ${i?null:this.renderMessageHeader(e,String(t))}
988
+ ${e.parts.map(s=>this.renderPart(s,e))}
989
+ </article>
990
+ `}isToolExecutionOnlyMessage(e){return e.role==="tool"&&e.parts.length>0&&e.parts.every(t=>t.type==="toolExecution")}renderMessageGroup(e,t,i,s){const o=this.groupDisclosureKey(t,i,s),r=this.disclosures.isOpen(o,s);return l`
991
+ ${this.renderScrollMarker(this.groupScrollMarkerId(i))}
992
+ <details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${r} @toggle=${n=>{this.onGroupToggle(o,n,s)}}>
993
+ <summary>
994
+ <b class="label">${s?"live events":"events"}</b>
995
+ <span>${Qf(e)}</span>
996
+ </summary>
997
+ <div class="group-body">
998
+ ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
999
+ <section class=${c?"group-msg tool-execution-shell":`group-msg ${n.role}`} data-index=${t+a} data-scroll-anchor-id=${this.eventAnchorKey(t+a)}>
1000
+ ${c?null:this.renderMessageHeader(n,`${String(t)}:${String(a)}`)}
1001
+ ${n.parts.map(p=>this.renderPart(p,n))}
1002
+ </section>
1003
+ `})}
1004
+ </div>
1005
+ </details>
1006
+ `}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`
1007
+ <div class="msg-header">
1008
+ <b class="label">${e.role}</b>
1009
+ <div class="msg-header-trailing">
1010
+ ${this.renderMessageActions(e,t)}
1011
+ <span class=${s?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${i.full} aria-label=${i.full} aria-expanded=${String(s)} @click=${()=>{this.expandedMetaKey=s?void 0:t}} @keydown=${o=>{this.onMetaKeydown(o,t,s)}}>${i.short}</span>
1012
+ </div>
1013
+ </div>
1014
+ `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
1015
+ <div class="msg-actions" aria-label="Message actions">
1016
+ <button type="button" class="msg-action" title=${i?"Copied":"Copy message"} aria-label=${`${i?"Copied":"Copy"} ${e.role} message`} @click=${s=>{this.copyMessage(e,t,s)}}>
1017
+ <span aria-hidden="true">${i?"✓":"⧉"}</span>
1018
+ </button>
1019
+ </div>
1020
+ `}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(`
1021
+
1022
+ `);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:"no info",full:"No Pi message metadata available"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`Model: ${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:Im.format(t),full:Mm.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>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
1023
+ <details class="part skill-invocation">
1024
+ <summary><b>[skill]</b> ${e.name}</summary>
1025
+ <small>${e.location}</small>
1026
+ <formatted-text .text=${e.content}></formatted-text>
1027
+ </details>
1028
+ `:e.type==="skillRead"?l`
1029
+ <div class="part skill-read">
1030
+ <strong>Loaded ${e.name}</strong>
1031
+ <small>read ${e.path}</small>
1032
+ </div>
1033
+ `: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`
1034
+ <details class="part" ?open=${e.isError}>
1035
+ <summary>${e.isError?"✖":"✓"} ${e.toolName} result</summary>
1036
+ <formatted-text .text=${e.text}></formatted-text>
1037
+ </details>
1038
+ `: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&&rg({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?sa(e):!0}isAtBottom(){const e=this.chat;return e?ia(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 Jf(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const o=this.chat;if(!(!o||t!==this.prependRestoreToken)){if(Xf(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<Zf){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=si(i,0,Math.max(0,e-1));return}this.currentConversationIndex=si(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(e===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return kr(e,t)??kr(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)}`}};j.styles=mf;F([d({attribute:!1})],j.prototype,"messages",2);F([d()],j.prototype,"sessionId",2);F([d({type:Number})],j.prototype,"messageStart",2);F([d({type:Number})],j.prototype,"messageEnd",2);F([d({type:Number})],j.prototype,"messageTotal",2);F([d({type:Boolean})],j.prototype,"hasMore",2);F([d({type:Boolean})],j.prototype,"loadingMore",2);F([d({type:Boolean})],j.prototype,"isReceivingPartialStream",2);F([d({type:Boolean})],j.prototype,"isCompacting",2);F([d({type:Number})],j.prototype,"pendingMessageCount",2);F([d({attribute:!1})],j.prototype,"status",2);F([d({attribute:!1})],j.prototype,"activity",2);F([d({attribute:!1})],j.prototype,"onLoadMore",2);F([z(".chat")],j.prototype,"chat",2);F([b()],j.prototype,"pinnedToBottom",2);F([b()],j.prototype,"expandedMetaKey",2);F([b()],j.prototype,"copiedMessageKey",2);F([b()],j.prototype,"currentConversationIndex",2);F([b()],j.prototype,"loadMoreRequested",2);j=F([E("chat-view")],j);class Tm extends to{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===Ys.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const o="element"in t?t.element:void 0;requestAnimationFrame(()=>{o instanceof HTMLElement&&o.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const fo=eo(Tm);var Am=Object.defineProperty,Em=Object.getOwnPropertyDescriptor,Li=(e,t,i,s)=>{for(var o=s>1?void 0:s?Em(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Am(t,i,o),o};let lt=class extends C{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1039
+ <div class="menu">
1040
+ ${this.items.map((e,t)=>l`
1041
+ <button class=${t===this.selectedIndex?"selected":""} ${fo(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1042
+ <strong>${e.insertText}</strong>
1043
+ <span>${e.detail}</span>
1044
+ ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1045
+ </button>
1046
+ `)}
1047
+ </div>
1048
+ `:null}};lt.styles=wf;Li([d({attribute:!1})],lt.prototype,"items",2);Li([d({type:Number})],lt.prototype,"selectedIndex",2);Li([d({attribute:!1})],lt.prototype,"onPick",2);lt=Li([E("autocomplete-menu")],lt);var Dm=Object.defineProperty,Wm=Object.getOwnPropertyDescriptor,V=(e,t,i,s)=>{for(var o=s>1?void 0:s?Wm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Dm(t,i,o),o};let U=class extends C{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 mo,this.readOnlyCompartment=new mo}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=Kt(i,t);s!==void 0&&pi(s,this.draft);const o=Kt(this.machineId,this.sessionId);this.draft=o!==void 0?bn(o):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=qs(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting;return l`
1049
+ <footer class=${t?"shell-mode":""}>
1050
+ <div class="editor-wrap">
1051
+ <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="Message pi" aria-disabled=${this.disabled?"true":"false"}></div>
1052
+ ${t?l`<div class="mode-hint">Shell command${e.excludeFromContext?" · excluded from context":""}</div>`:null}
1053
+ ${this.isCompacting&&!t?l`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
1054
+ <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${s=>{this.pick(s)}}></autocomplete-menu>
1055
+ </div>
1056
+ <div class="actions">
1057
+ ${this.renderCompactStatus()}
1058
+ <button ?disabled=${this.disabled} title=${i?"Queue until the current activity finishes":"Send message"} @click=${()=>{this.send("followUp")}}>${i?"Queue":"Send"}</button>
1059
+ ${this.canSteer&&!this.isCompacting?l`<button ?disabled=${this.disabled} title="Steer the current response before the next model call" @click=${()=>{this.send("steer")}}>Steer</button>`:null}
1060
+ <button ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} @click=${()=>this.onStop?.()}>Stop</button>
1061
+ </div>
1062
+ </footer>
1063
+ `}focusInput(){this.editor?.focus()}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"no model",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return l`
1064
+ <div class="compact-status" aria-label="Session status">
1065
+ <button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1066
+ <button class="select-thinking" title="Select thinking level" @click=${()=>this.onSelectThinking?.()}>think ${e.thinkingLevel??"off"}</button>
1067
+ </div>
1068
+ `}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new tt({parent:this.editorHost,state:Ni.create({doc:this.draft,extensions:[$a(),Wa(),Pa(),Ra.of(" "),Ca(Da,{fallback:!0}),tt.lineWrapping,tt.contentAttributes.of(e=>Nm(e.state.sliceDoc(0,e.state.selection.main.head))),Ia("Message pi... Use / for commands, @ for tracked files, @ space for all files"),this.editableCompartment.of(tt.editable.of(!this.disabled)),this.readOnlyCompartment.of(Ni.readOnly.of(this.disabled)),tt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Ma.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=>_a(e)||Ea(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>vo.shift?.(e)??!1},{key:"Backspace",run:e=>Oa(e)},...Ta,...Aa])]})}))}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:bo.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(tt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(Ni.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Kt(this.machineId,this.sessionId);t!==void 0&&pi(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await O.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(_m);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 O.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(Om);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=tp(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:o,detail:s.kind,...s.path.endsWith("/")&&o.endsWith('"')?{cursorOffset:o.length-1}:{}}})}}currentTrigger(){return kn(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):vo.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,o=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:o,insert:`${e.insertText}${i}`},selection:bo.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){const t=this.draft.trim();if(t===""||this.disabled)return;this.draft="";const i=Kt(this.machineId,this.sessionId);i!==void 0&&Hs(i),this.completions=[],this.onSend?.(t,this.canSteer||this.isCompacting?e:void 0)}};U.styles=Sf;V([d({type:Boolean})],U.prototype,"disabled",2);V([d()],U.prototype,"sessionId",2);V([d()],U.prototype,"cwd",2);V([d()],U.prototype,"machineId",2);V([d({type:Boolean})],U.prototype,"canSteer",2);V([d({type:Boolean})],U.prototype,"isCompacting",2);V([d({type:Boolean})],U.prototype,"canStop",2);V([d({attribute:!1})],U.prototype,"status",2);V([d({attribute:!1})],U.prototype,"onSend",2);V([d({attribute:!1})],U.prototype,"onStop",2);V([d({attribute:!1})],U.prototype,"onSelectModel",2);V([d({attribute:!1})],U.prototype,"onSelectThinking",2);V([z(".markdown-editor")],U.prototype,"editorHost",2);V([b()],U.prototype,"draft",2);V([b()],U.prototype,"completions",2);V([b()],U.prototype,"selectedIndex",2);U=V([E("prompt-editor")],U);function Kt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return vn(e,t)}function _m(){return[]}function Om(){return[]}const Lm={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},jm={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function Nm(e){return qs(e).kind==="normal"?Lm:jm}function Vt(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 zm(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Fm=Object.defineProperty,Bm=Object.getOwnPropertyDescriptor,ba=(e,t,i,s)=>{for(var o=s>1?void 0:s?Bm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Fm(t,i,o),o};let Si=class extends C{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">No session status yet</div>`;const t=e.contextUsage,i=t?t.percent==null?`context ${Vt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Vt(t.contextWindow)}`:"context unknown",s=e.tokens;return l`
1069
+ <div class="bar">
1070
+ <span>↑${Vt(s.input)}</span>
1071
+ <span>↓${Vt(s.output)}</span>
1072
+ <span class="context">${i}</span>
1073
+ <span>${zm(e.cost)}</span>
1074
+ ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} queued</span>`:null}
1075
+ </div>
1076
+ `}};Si.styles=bf;ba([d({attribute:!1})],Si.prototype,"status",2);Si=ba([E("status-bar")],Si);var Um=Object.defineProperty,Hm=Object.getOwnPropertyDescriptor,Le=(e,t,i,s)=>{for(var o=s>1?void 0:s?Hm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Um(t,i,o),o};let Pe=class extends C{constructor(){super(...arguments),this.title="Select",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1077
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1078
+ <section @mousedown=${t=>{t.stopPropagation()}}>
1079
+ <header>
1080
+ <strong>${this.title}</strong>
1081
+ <button @click=${()=>this.onCancel?.()}>×</button>
1082
+ </header>
1083
+ ${this.searchable?l`<input placeholder="Search" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1084
+ <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1085
+ ${e.map((t,i)=>l`
1086
+ <button class=${i===this.selectedIndex?"selected":""} ${fo(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1087
+ <span>${t.label}</span>
1088
+ ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1089
+ </button>
1090
+ `)}
1091
+ ${e.length===0?l`<div class="empty">No matching options</div>`:null}
1092
+ </div>
1093
+ </section>
1094
+ </div>
1095
+ `}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)}}};Pe.styles=Yn;Le([d()],Pe.prototype,"title",2);Le([d({type:Boolean})],Pe.prototype,"searchable",2);Le([d({attribute:!1})],Pe.prototype,"options",2);Le([d({attribute:!1})],Pe.prototype,"selectedValue",2);Le([d({attribute:!1})],Pe.prototype,"onPick",2);Le([d({attribute:!1})],Pe.prototype,"onCancel",2);Le([b()],Pe.prototype,"selectedIndex",2);Le([b()],Pe.prototype,"query",2);Pe=Le([E("command-picker")],Pe);var qm=Object.defineProperty,Km=Object.getOwnPropertyDescriptor,Xe=(e,t,i,s)=>{for(var o=s>1?void 0:s?Km(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&qm(t,i,o),o};let _e=class extends C{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1096
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1097
+ <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1098
+ <header>
1099
+ <input
1100
+ .value=${this.queryText}
1101
+ placeholder="Search actions..."
1102
+ @input=${t=>{t.target instanceof HTMLInputElement&&(this.queryText=t.target.value,this.selectedIndex=0)}}
1103
+ >
1104
+ <button title="Close" @click=${()=>this.onCancel?.()}>×</button>
1105
+ </header>
1106
+ <div class="options">
1107
+ ${e.length===0?l`<div class="empty">No actions found.</div>`:e.map((t,i)=>l`
1108
+ <button class=${i===this.selectedIndex?"selected":""} ${fo(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1109
+ <span class="main">
1110
+ <strong>${t.title}</strong>
1111
+ ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1112
+ </span>
1113
+ ${t.shortcut!==void 0?l`<kbd>${ei(t.shortcut)}</kbd>`:null}
1114
+ ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1115
+ </button>
1116
+ `)}
1117
+ </div>
1118
+ </section>
1119
+ </div>
1120
+ `}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=yf;Xe([d({attribute:!1})],_e.prototype,"actions",2);Xe([d({attribute:!1})],_e.prototype,"onRun",2);Xe([d({attribute:!1})],_e.prototype,"onCancel",2);Xe([z("input")],_e.prototype,"input",2);Xe([b()],_e.prototype,"queryText",2);Xe([b()],_e.prototype,"selectedIndex",2);_e=Xe([E("action-palette")],_e);var Vm=Object.defineProperty,Gm=Object.getOwnPropertyDescriptor,ve=(e,t,i,s)=>{for(var o=s>1?void 0:s?Gm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Vm(t,i,o),o};let ie=class extends C{render(){const e=this.state;return e===void 0?null:l`
1121
+ <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1122
+ <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1123
+ <header>
1124
+ <strong>${this.dialogTitle(e)}</strong>
1125
+ <button title="Close" @click=${()=>{this.cancel()}}>×</button>
1126
+ </header>
1127
+ ${this.renderBody(e)}
1128
+ </section>
1129
+ </div>
1130
+ `}updated(){this.focusInputIfNeeded()}dialogTitle(e){switch(e.step){case"method":return"Configure provider authentication";case"providers":return e.authType===void 0?"Select provider authentication":e.authType==="oauth"?"Select subscription provider":"Select API key provider";case"apiKey":return`API key for ${e.provider.name}`;case"oauth":return`Login to ${e.flow.providerName}`;case"logout":return"Remove stored provider authentication"}}renderBody(e){switch(e.step){case"method":return l`
1131
+ <div class="options">
1132
+ <button @click=${()=>{this.onChooseMethod?.("oauth")}}><span>Use a subscription</span><small>ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot</small></button>
1133
+ <button @click=${()=>{this.onChooseMethod?.("api_key")}}><span>Use an API key</span><small>Store an API key in pi auth.json</small></button>
1134
+ </div>
1135
+ `;case"providers":return l`<div class="options">${e.providers.length===0?l`<div class="empty">No providers available.</div>`:e.providers.map(t=>this.renderProviderButton(t))}</div>`;case"apiKey":return l`
1136
+ <div class="form">
1137
+ <p>Enter the API key for <strong>${e.provider.name}</strong>. It will be stored by pi in <code>auth.json</code>.</p>
1138
+ <input type="password" autocomplete="off" placeholder="API key" .value=${e.value} @input=${t=>{t.target instanceof HTMLInputElement&&this.onApiKeyInput?.(t.target.value)}}>
1139
+ ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1140
+ <div class="actions"><button @click=${()=>{this.cancel()}}>Cancel</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?"Saving…":"Save API key"}</button></div>
1141
+ </div>
1142
+ `;case"oauth":return this.renderOAuth(e);case"logout":return l`<div class="options">${e.providers.length===0?l`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(t=>l`
1143
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Or(t.authType)}</small></button>
1144
+ `)}</div>`}}renderProviderButton(e){return l`
1145
+ <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1146
+ <span>${e.name}${e.status.source!==void 0?l` <em>${Zm(e)}</em>`:null}</span>
1147
+ <small>${e.id} · ${Or(e.authType)}</small>
1148
+ </button>
1149
+ `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1150
+ <div class="form">
1151
+ ${t.auth!==void 0?l`
1152
+ <p>Open this authorization link:</p>
1153
+ <p><a href=${t.auth.url} target="_blank" rel="noreferrer">${t.auth.url}</a></p>
1154
+ ${t.auth.instructions!==void 0?l`<p class="warning">${t.auth.instructions}</p>`:null}
1155
+ `:l`<p>Starting login flow…</p>`}
1156
+ ${t.progress.length>0?l`<ul class="progress">${t.progress.map(o=>l`<li>${o}</li>`)}</ul>`:null}
1157
+ ${i!==void 0?l`
1158
+ <label>${i.message}</label>
1159
+ <input .value=${e.inputValue??""} placeholder=${i.placeholder??""} @input=${o=>{o.target instanceof HTMLInputElement&&this.onOAuthInput?.(o.target.value)}}>
1160
+ <div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button><button class="primary" ?disabled=${e.responding===!0} @click=${()=>{this.onOAuthRespond?.()}}>Submit</button></div>
1161
+ `:null}
1162
+ ${s!==void 0?l`
1163
+ <p>${s.message}</p>
1164
+ <div class="inline-options">${s.options.map(o=>l`<button @click=${()=>{this.onOAuthRespond?.(o.value)}}>${o.label}</button>`)}</div>
1165
+ `:null}
1166
+ ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1167
+ ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??t.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
1168
+ ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
1169
+ </div>
1170
+ `}focusInputIfNeeded(){const e=Qm(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?.()}};ie.styles=[Yn,W`
1171
+ .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1172
+ .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1173
+ .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
1174
+ .form code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-surface); padding: 1px 4px; }
1175
+ label { color: var(--pi-muted); }
1176
+ .actions { display: flex; justify-content: flex-end; gap: 8px; }
1177
+ .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; }
1178
+ .actions button.primary { border-color: var(--pi-success-border); background: var(--pi-success-surface); color: var(--pi-success); }
1179
+ .actions button:disabled { opacity: .6; cursor: wait; }
1180
+ .warning { color: var(--pi-warning); }
1181
+ .error-text { color: var(--pi-danger); }
1182
+ .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1183
+ .inline-options { display: grid; gap: 8px; }
1184
+ em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1185
+ `];ve([d({attribute:!1})],ie.prototype,"state",2);ve([d({attribute:!1})],ie.prototype,"onChooseMethod",2);ve([d({attribute:!1})],ie.prototype,"onSelectProvider",2);ve([d({attribute:!1})],ie.prototype,"onApiKeyInput",2);ve([d({attribute:!1})],ie.prototype,"onSaveApiKey",2);ve([d({attribute:!1})],ie.prototype,"onLogoutProvider",2);ve([d({attribute:!1})],ie.prototype,"onOAuthInput",2);ve([d({attribute:!1})],ie.prototype,"onOAuthRespond",2);ve([d({attribute:!1})],ie.prototype,"onOAuthCancel",2);ve([d({attribute:!1})],ie.prototype,"onCancel",2);ve([z("input")],ie.prototype,"input",2);ie=ve([E("auth-dialog")],ie);function Or(e){return e==="oauth"?"subscription":"API key"}function Qm(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 Zm(e){if(e.status.source===void 0)return"";switch(e.status.source){case"stored":return"✓ configured";case"environment":return`✓ env${e.status.label===void 0?"":`: ${e.status.label}`}`;case"runtime":return"✓ runtime";case"fallback":return"✓ custom key";case"models_json_key":return"✓ models.json key";case"models_json_command":return"✓ models.json command";default:return""}}var Jm=Object.defineProperty,Xm=Object.getOwnPropertyDescriptor,Ae=(e,t,i,s)=>{for(var o=s>1?void 0:s?Xm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Jm(t,i,o),o};let fe=class extends C{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 O.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`
1186
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
1187
+ <section @click=${e=>{e.stopPropagation()}}>
1188
+ <header>
1189
+ <strong>Add project</strong>
1190
+ <button @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
1191
+ </header>
1192
+ <div class="body">
1193
+ <label>
1194
+ Project folder
1195
+ <input .value=${this.path} @input=${e=>{this.onPathInput(e)}} @keydown=${e=>{this.onKeyDown(e)}} placeholder="/path/to/project or ~/code/project" autofocus />
1196
+ </label>
1197
+ <div class="suggestions">
1198
+ ${this.loading?l`<div class="hint">Loading folders…</div>`:null}
1199
+ ${this.suggestions.map((e,t)=>l`
1200
+ <button class=${t===this.selected?"selected":""} @click=${()=>{this.pick(e)}}>
1201
+ ${e.path}
1202
+ </button>
1203
+ `)}
1204
+ ${!this.loading&&this.suggestions.length===0?l`<div class="hint">No matching folders. Enter a new path to create it.</div>`:null}
1205
+ </div>
1206
+ <label class="check">
1207
+ <input type="checkbox" .checked=${this.createMissing} @change=${e=>{this.onCreateMissingChange(e)}} />
1208
+ Create the folder if it does not exist
1209
+ </label>
1210
+ </div>
1211
+ <footer>
1212
+ <button @click=${()=>{this.onCancel?.()}}>Cancel</button>
1213
+ <button class="primary" ?disabled=${this.path.trim()===""} @click=${()=>{this.submit()}}>Add project</button>
1214
+ </footer>
1215
+ </section>
1216
+ </div>
1217
+ `}};fe.styles=W`
1218
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1219
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1220
+ 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; }
1221
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1222
+ footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1223
+ .body { display: grid; gap: 12px; padding: 12px; min-height: 0; }
1224
+ label { display: grid; gap: 6px; color: var(--pi-muted); }
1225
+ 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; }
1226
+ .check { display: flex; grid-template-columns: auto 1fr; align-items: center; color: var(--pi-text); }
1227
+ .suggestions { min-height: 90px; max-height: 320px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); }
1228
+ .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; }
1229
+ .suggestions button.selected, .suggestions button:hover { background: var(--pi-selection-bg); }
1230
+ .hint { padding: 12px; color: var(--pi-muted); }
1231
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1232
+ header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1233
+ .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1234
+ button:disabled { opacity: .5; cursor: not-allowed; }
1235
+ `;Ae([d({attribute:!1})],fe.prototype,"onSubmit",2);Ae([d({attribute:!1})],fe.prototype,"onCancel",2);Ae([d()],fe.prototype,"machineId",2);Ae([b()],fe.prototype,"path",2);Ae([b()],fe.prototype,"createMissing",2);Ae([b()],fe.prototype,"suggestions",2);Ae([b()],fe.prototype,"selected",2);Ae([b()],fe.prototype,"loading",2);Ae([z("input")],fe.prototype,"pathInput",2);fe=Ae([E("project-dialog")],fe);var Ym=Object.defineProperty,ev=Object.getOwnPropertyDescriptor,Ee=(e,t,i,s)=>{for(var o=s>1?void 0:s?ev(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ym(t,i,o),o};let ge=class extends C{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=tv(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"&&ss(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===""||ss(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?ss(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1236
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
1237
+ <section @click=${s=>{s.stopPropagation()}}>
1238
+ <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
1239
+ <header>
1240
+ <strong>Add machine</strong>
1241
+ <button type="button" @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
1242
+ </header>
1243
+ <div class="body">
1244
+ ${this.error===""?null:l`<div class="dialog-error" role="alert">${this.error}</div>`}
1245
+ <label>
1246
+ Remote PI WEB URL
1247
+ <input name="baseUrl" type="url" .value=${this.url} @input=${s=>{this.handleUrlInput(s)}} placeholder="http://dev-box.local:8504" autocomplete="url" inputmode="url" autofocus />
1248
+ </label>
1249
+ <small class=${t===void 0?"hint":"field-error"}>${t??"Enter the reachable base URL first, including http:// or https://."}</small>
1250
+ ${e?l`
1251
+ <label>
1252
+ Machine name
1253
+ <input name="name" type="text" .value=${this.name} @input=${s=>{this.handleNameInput(s)}} placeholder=${this.previousSuggestedName||"Dev Box"} autocomplete="off" />
1254
+ </label>
1255
+ <small class="hint">Suggested from the URL. Edit it to use a friendlier sidebar label.</small>
1256
+ <label>
1257
+ Bearer token <span class="optional">optional</span>
1258
+ <input name="token" type="password" .value=${this.token} @input=${s=>{this.handleTokenInput(s)}} placeholder="Leave blank if the remote machine does not require one" autocomplete="off" />
1259
+ </label>
1260
+ <small class="hint">Paste only the token value; PI WEB sends it as an Authorization: Bearer header.</small>
1261
+ `:l`<p class="hint intro">After you enter a URL, PI WEB will suggest a machine name and let you add an optional bearer token.</p>`}
1262
+ </div>
1263
+ <footer>
1264
+ <button type="button" @click=${()=>{this.onCancel?.()}}>Cancel</button>
1265
+ <button class="primary" type="submit" ?disabled=${!i}>${this.submitting?"Adding…":"Add machine"}</button>
1266
+ </footer>
1267
+ </form>
1268
+ </section>
1269
+ </div>
1270
+ `}};ge.styles=W`
1271
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1272
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1273
+ 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; }
1274
+ form { display: flex; flex-direction: column; max-height: inherit; min-height: 0; }
1275
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1276
+ footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1277
+ .body { display: grid; gap: 8px; padding: 12px; min-height: 0; overflow: auto; }
1278
+ label { display: grid; gap: 6px; color: var(--pi-muted); }
1279
+ 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; }
1280
+ input:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 1px; }
1281
+ .hint { color: var(--pi-muted); }
1282
+ .intro { margin: 4px 0 0; line-height: 1.4; }
1283
+ .optional { color: var(--pi-muted); font-weight: 400; }
1284
+ .field-error { color: var(--pi-danger); }
1285
+ .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; }
1286
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1287
+ header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1288
+ .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1289
+ button:disabled { opacity: .5; cursor: not-allowed; }
1290
+ `;Ee([d({attribute:!1})],ge.prototype,"onSubmit",2);Ee([d({attribute:!1})],ge.prototype,"onCancel",2);Ee([d()],ge.prototype,"error",2);Ee([b()],ge.prototype,"url",2);Ee([b()],ge.prototype,"name",2);Ee([b()],ge.prototype,"token",2);Ee([b()],ge.prototype,"submitting",2);Ee([z("input[name='baseUrl']")],ge.prototype,"urlInput",2);Ee([z("input[name='name']")],ge.prototype,"nameInput",2);ge=Ee([E("machine-dialog")],ge);function tv(e){const t=e.trim();if(t==="")return"";const i=Lr(t)??Lr(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):iv(t)}function ss(e){const t=e.trim();if(t==="")return"Remote PI WEB URL is required.";let i;try{i=new URL(t)}catch{return"Enter a valid URL including http:// or https://."}if(i.protocol!=="http:"&&i.protocol!=="https:")return"Use an http:// or https:// URL.";if(i.username!==""||i.password!=="")return"Do not include credentials in the machine URL.";if(i.search!==""||i.hash!=="")return"Do not include a query string or fragment."}function Lr(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function iv(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 sv(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function ov(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(`
1291
+ `):""}}function rv(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins}},s=e.host.trim(),o=e.port.trim();if(s!==""&&(i.host=s),o!==""){const r=Number(o);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("Port must be an integer from 1 to 65535.");i.port=r}return i.allowedHosts=e.allowedHostsMode==="all"?!0:nv(e.allowedHostsText),i}function nv(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}var av=Object.defineProperty,lv=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var o=s>1?void 0:s?lv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&av(t,i,o),o};let me=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=sv(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=ov(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1292
+ <div class="section-heading">
1293
+ <div>
1294
+ <h2>General configuration</h2>
1295
+ <p>Update the JSON config file PI WEB is using. Host and port changes are saved immediately, but require the web service to restart before the running server binds to the new address.</p>
1296
+ </div>
1297
+ <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1298
+ </div>
1299
+ ${this.renderMessages()}
1300
+ ${e===void 0&&this.loading?l`<div class="loading-card">Loading configuration…</div>`:l`
1301
+ <div class="config-path-card">
1302
+ <span>Config file</span>
1303
+ <code>${e?.path??"Unknown"}</code>
1304
+ <small>${e?.exists===!0?"Existing file":"This file will be created on save"}</small>
1305
+ </div>
1306
+ <form class="config-form" @submit=${t=>{this.saveConfig(t)}}>
1307
+ <label class="field">
1308
+ <span class="field-heading">
1309
+ <span>Host</span>
1310
+ ${this.renderOverrideBadge("host")}
1311
+ </span>
1312
+ <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:jr(t)})}}>
1313
+ <small>Address the web server should bind to. Leave empty to use PI WEB's default.</small>
1314
+ </label>
1315
+
1316
+ <label class="field">
1317
+ <span class="field-heading">
1318
+ <span>Port</span>
1319
+ ${this.renderOverrideBadge("port")}
1320
+ </span>
1321
+ <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:jr(t)})}}>
1322
+ <small>TCP port from 1 to 65535. Leave empty to use PI WEB's default.</small>
1323
+ </label>
1324
+
1325
+ <div class="field">
1326
+ <span class="field-heading">
1327
+ <span>Allowed hosts</span>
1328
+ ${this.renderOverrideBadge("allowedHosts")}
1329
+ </span>
1330
+ <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:dv(t)==="all"?"all":"list"})}}>
1331
+ <option value="list">Only listed hosts</option>
1332
+ <option value="all">Allow every host</option>
1333
+ </select>
1334
+ <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:pv(t)})}}></textarea>
1335
+ <small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
1336
+ </div>
1337
+
1338
+ ${this.renderEffectiveConfig()}
1339
+
1340
+ <footer class="form-actions">
1341
+ <button class="primary" ?disabled=${this.loading||this.saving}>${this.saving?"Saving…":"Save config"}</button>
1342
+ </footer>
1343
+ </form>
1344
+ `}
1345
+ `}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">environment override</span>`}renderEffectiveConfig(){const e=this.configResponse?.effectiveConfig??{};return l`
1346
+ <section class="effective-card" aria-label="Effective configuration summary">
1347
+ <h3>Effective after environment overrides</h3>
1348
+ <dl>
1349
+ <div><dt>Host</dt><dd>${e.host??l`<span class="muted">127.0.0.1 default</span>`}</dd></div>
1350
+ <div><dt>Port</dt><dd>${e.port??l`<span class="muted">8504 default</span>`}</dd></div>
1351
+ <div><dt>Allowed hosts</dt><dd>${cv(e.allowedHosts)}</dd></div>
1352
+ </dl>
1353
+ </section>
1354
+ `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(rv(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=hv(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};me.styles=W`
1355
+ :host { display: block; }
1356
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1357
+ .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1358
+ h2, h3, p { margin: 0; }
1359
+ h2 { font-size: 17px; line-height: 1.25; }
1360
+ h3 { font-size: 13px; line-height: 1.3; }
1361
+ p { color: var(--pi-muted); line-height: 1.45; }
1362
+ button, input, select, textarea { font: inherit; }
1363
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1364
+ button:disabled { opacity: .55; cursor: not-allowed; }
1365
+ .secondary { flex: 0 0 auto; }
1366
+ .message, .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1367
+ .message { margin-bottom: 12px; }
1368
+ .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1369
+ .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1370
+ .loading-card { color: var(--pi-muted); }
1371
+ .config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
1372
+ .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1373
+ 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; }
1374
+ .config-path-card small, .field small { color: var(--pi-muted); }
1375
+ .config-form { display: grid; gap: 14px; }
1376
+ .field { display: grid; gap: 7px; }
1377
+ .field-heading { display: flex; align-items: center; gap: 8px; }
1378
+ 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; }
1379
+ input:focus, select:focus, textarea:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1380
+ textarea { resize: vertical; min-height: 94px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1381
+ textarea:disabled { opacity: .55; }
1382
+ .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; }
1383
+ .effective-card { display: grid; gap: 10px; }
1384
+ .effective-card dl { display: grid; gap: 8px; margin: 0; }
1385
+ .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
1386
+ dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
1387
+ .muted { color: var(--pi-muted); }
1388
+ .form-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
1389
+ .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
1390
+
1391
+ @media (max-width: 760px) {
1392
+ .section-heading { display: grid; gap: 12px; }
1393
+ .section-heading .secondary { justify-self: start; }
1394
+ .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1395
+ }
1396
+ `;De([d({attribute:!1})],me.prototype,"configResponse",2);De([d({type:Boolean})],me.prototype,"loading",2);De([d({type:Boolean})],me.prototype,"saving",2);De([d()],me.prototype,"error",2);De([d()],me.prototype,"savedMessage",2);De([d({attribute:!1})],me.prototype,"onReload",2);De([d({attribute:!1})],me.prototype,"onSave",2);De([b()],me.prototype,"draft",2);De([b()],me.prototype,"localError",2);me=De([E("settings-general-panel")],me);function cv(e){return e===!0?"Any host":Array.isArray(e)?e.length===0?l`<span class="muted">None listed</span>`:e.join(", "):l`<span class="muted">Unset</span>`}function jr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function dv(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function pv(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function hv(e){return e instanceof Error?e.message:String(e)}var uv=Object.defineProperty,fv=Object.getOwnPropertyDescriptor,je=(e,t,i,s)=>{for(var o=s>1?void 0:s?fv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&uv(t,i,o),o};let Re=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1397
+ <div class="section-heading">
1398
+ <div>
1399
+ <h2>Plugins</h2>
1400
+ <p>Enable or disable discovered PI WEB plugins. Changes apply after reloading the browser tab; already-loaded plugin code is not unloaded from the current page.</p>
1401
+ </div>
1402
+ <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1403
+ </div>
1404
+ ${this.renderMessages()}
1405
+ <div class="plugin-note">Config key: <code>plugins</code>. Plugins are enabled unless their entry sets <code>enabled</code> to <code>false</code>.</div>
1406
+ ${this.loading&&e.length===0?l`<div class="loading-card">Loading plugins…</div>`:e.length===0?l`<div class="loading-card">No external or bundled plugins discovered.</div>`:l`
1407
+ <div class="plugin-list">
1408
+ ${e.map(t=>this.renderPlugin(t))}
1409
+ </div>
1410
+ `}
1411
+ `}renderMessages(){return this.error!==""?l`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage} Reload the browser tab to apply plugin changes.</div>`:null}renderPlugin(e){const t=this.configResponse?.config.plugins?.[e.id],i=t?.enabled===!1?"Config disabled":t?.enabled===!0?"Config enabled":"Default enabled";return l`
1412
+ <article class=${`plugin-card${e.enabled?"":" disabled"}`}>
1413
+ <div class="plugin-main">
1414
+ <strong>${e.id}</strong>
1415
+ <small>${e.source} · ${e.scope}${e.machineSpecific?" · machine-specific":""}</small>
1416
+ <small>${i}</small>
1417
+ </div>
1418
+ <label class="toggle">
1419
+ <input type="checkbox" .checked=${e.enabled} ?disabled=${this.saving} @change=${s=>{this.togglePlugin(e,s)}}>
1420
+ <span>${e.enabled?"Enabled":"Disabled"}</span>
1421
+ </label>
1422
+ </article>
1423
+ `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Re.styles=W`
1424
+ :host { display: block; }
1425
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1426
+ .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1427
+ h2, p { margin: 0; }
1428
+ h2 { font-size: 17px; line-height: 1.25; }
1429
+ p { color: var(--pi-muted); line-height: 1.45; }
1430
+ button, input { font: inherit; }
1431
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1432
+ button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
1433
+ .secondary { flex: 0 0 auto; }
1434
+ .message, .loading-card, .plugin-note, .plugin-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1435
+ .message { margin-bottom: 12px; }
1436
+ .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1437
+ .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1438
+ .loading-card, .plugin-note { color: var(--pi-muted); }
1439
+ .plugin-note { margin-bottom: 14px; }
1440
+ 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; }
1441
+ .plugin-list { display: grid; gap: 10px; }
1442
+ .plugin-card { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center; }
1443
+ .plugin-card.disabled { opacity: .75; }
1444
+ .plugin-main { min-width: 0; display: grid; gap: 3px; }
1445
+ .plugin-main strong, .plugin-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1446
+ .plugin-main small { color: var(--pi-muted); }
1447
+ .toggle { display: inline-flex; align-items: center; gap: 7px; white-space: nowrap; }
1448
+ .toggle input { width: 18px; height: 18px; accent-color: var(--pi-accent); }
1449
+
1450
+ @media (max-width: 760px) {
1451
+ .section-heading { display: grid; gap: 12px; }
1452
+ .section-heading .secondary { justify-self: start; }
1453
+ .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1454
+ .toggle { justify-self: start; }
1455
+ }
1456
+ `;je([d({attribute:!1})],Re.prototype,"pluginsResponse",2);je([d({attribute:!1})],Re.prototype,"configResponse",2);je([d({type:Boolean})],Re.prototype,"loading",2);je([d({type:Boolean})],Re.prototype,"saving",2);je([d()],Re.prototype,"error",2);je([d()],Re.prototype,"savedMessage",2);je([d({attribute:!1})],Re.prototype,"onReload",2);je([d({attribute:!1})],Re.prototype,"onTogglePlugin",2);Re=je([E("settings-plugins-panel")],Re);var gv=Object.defineProperty,mv=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var o=s>1?void 0:s?mv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&gv(t,i,o),o};const Nr={capture:!0};let se=class extends C{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=Tn(e);if(i===void 0){this.localError="Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.";return}if(t.tokens.length===0&&!At(i)){this.localError="Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.";return}const s=[...t.tokens,i];this.localError="",this.drafts={[t.actionId]:s.join(" ")},this.recording={actionId:t.actionId,tokens:s},this.armRecordingTimer()}}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.drafts={},this.localError="",this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){const e=yv(this.actions),t=this.shortcutResolutions();return l`
1457
+ <div class="section-heading">
1458
+ <div>
1459
+ <h2>Keyboard shortcuts</h2>
1460
+ <p>Edit app shortcuts by action. Type a shortcut such as <code>mod+k</code> or <code>mod+g p</code>, record one from the keyboard, disable it with None, or reset it to the default. When shortcuts conflict, custom shortcuts win before defaults; ties are resolved by action id, and shorter shortcuts shadow longer sequences with the same prefix.</p>
1461
+ </div>
1462
+ <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1463
+ </div>
1464
+ ${this.renderMessages()}
1465
+ ${this.configResponse===void 0&&this.loading?l`<div class="loading-card">Loading shortcuts…</div>`:l`
1466
+ <div class="config-path-card">
1467
+ <span>Config file</span>
1468
+ <code>${this.configResponse?.path??"Unknown"}</code>
1469
+ <small>Shortcut overrides are saved under <code>shortcuts</code>. A value of <code>null</code> disables the action shortcut.</small>
1470
+ </div>
1471
+ ${e.length===0?l`<div class="loading-card">No actions registered.</div>`:e.map(i=>l`
1472
+ <section class="shortcut-group">
1473
+ <h3>${i.name}</h3>
1474
+ <div class="shortcut-list">
1475
+ ${i.actions.map(s=>this.renderShortcutRow(s,t.get(s.id)))}
1476
+ </div>
1477
+ </section>
1478
+ `)}
1479
+ `}
1480
+ `}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}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=xi(e.id,i),o=$v(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:Ki(r),a=n?.ok===!0?n.shortcut:kv(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&r.trim()!==""?"custom":o,h=this.recordingHint(e.id),f=wv(t);return l`
1481
+ <article class=${vv(t)}>
1482
+ <div class="shortcut-main">
1483
+ <strong>${e.title}</strong>
1484
+ ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1485
+ <small class="shortcut-id">${e.id}</small>
1486
+ <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${ei(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1487
+ </div>
1488
+ <div class="shortcut-editor">
1489
+ <div class="shortcut-status">
1490
+ ${a!==void 0&&a!==""?l`<kbd>${ei(a)}</kbd>`:l`<span class="unassigned">${o==="disabled"?"Disabled":"Unassigned"}</span>`}
1491
+ <small class=${u}>${Pv(u)}${p?" · Unsaved":""}</small>
1492
+ ${f===void 0?null:l`<small class=${bv(t)}>${f}</small>`}
1493
+ </div>
1494
+ <label class="shortcut-input-label">
1495
+ <span>Shortcut</span>
1496
+ <input
1497
+ class="shortcut-input"
1498
+ data-action-id=${e.id}
1499
+ .value=${r}
1500
+ placeholder=${e.shortcut??"mod+k"}
1501
+ autocomplete="off"
1502
+ autocapitalize="off"
1503
+ spellcheck="false"
1504
+ ?disabled=${this.saving}
1505
+ @input=${v=>{this.updateDraft(e.id,Rv(v))}}
1506
+ >
1507
+ </label>
1508
+ ${h!==""?l`<small class="recording-hint">${h}</small>`:null}
1509
+ <div class="shortcut-actions">
1510
+ <button class="primary" ?disabled=${this.loading||this.saving||!p||r.trim()===""} @click=${()=>{this.saveShortcut(e)}}>Save</button>
1511
+ <button ?disabled=${this.loading||this.saving} @click=${()=>{this.toggleRecording(e.id)}}>${this.recording?.actionId===e.id?"Cancel recording":"Record"}</button>
1512
+ <button ?disabled=${this.loading||this.saving||s===null} @click=${()=>{this.setShortcutNone(e.id)}}>None</button>
1513
+ <button ?disabled=${this.loading||this.saving||!c} @click=${()=>{this.resetShortcut(e.id)}}>Reset</button>
1514
+ </div>
1515
+ </div>
1516
+ </article>
1517
+ `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=xi(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${ei(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=Ki(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},o=t===void 0?xv(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(Gs(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const o=Ki(s);o.ok&&(e[t]=o.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},In)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||(window.addEventListener("keydown",this.onRecordKeyDown,Nr),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,Nr),this.recordingListenerActive=!1)}};se.styles=W`
1518
+ :host { display: block; }
1519
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1520
+ .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1521
+ h2, h3, p { margin: 0; }
1522
+ h2 { font-size: 17px; line-height: 1.25; }
1523
+ h3 { font-size: 13px; line-height: 1.3; }
1524
+ p { color: var(--pi-muted); line-height: 1.45; }
1525
+ button, input { font: inherit; }
1526
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1527
+ button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
1528
+ .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
1529
+ .secondary { flex: 0 0 auto; }
1530
+ .message, .loading-card, .config-path-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1531
+ .message { margin-bottom: 12px; }
1532
+ .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1533
+ .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1534
+ .loading-card, .config-path-card { color: var(--pi-muted); }
1535
+ .config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
1536
+ .config-path-card span { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1537
+ 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; }
1538
+ .shortcut-group { margin: 0 0 16px; }
1539
+ .shortcut-group h3 { margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
1540
+ .shortcut-list { border: 1px solid var(--pi-border); border-radius: 10px; overflow: hidden; }
1541
+ .shortcut-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(360px, 48%); gap: 14px; align-items: start; padding: 12px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-surface); }
1542
+ .shortcut-row.shadowed { background: color-mix(in srgb, var(--pi-warning) 5%, var(--pi-surface)); }
1543
+ .shortcut-row.shadowing { background: color-mix(in srgb, var(--pi-accent) 5%, var(--pi-surface)); }
1544
+ .shortcut-row:last-child { border-bottom: 0; }
1545
+ .shortcut-main { min-width: 0; display: grid; gap: 4px; }
1546
+ .shortcut-main strong, .shortcut-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1547
+ .shortcut-main small { color: var(--pi-muted); }
1548
+ .shortcut-id { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1549
+ .shortcut-editor { min-width: 0; display: grid; gap: 8px; }
1550
+ .shortcut-status { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
1551
+ .shortcut-status small { color: var(--pi-muted); font-size: 11px; }
1552
+ .shortcut-status small.custom { color: var(--pi-accent); }
1553
+ .shortcut-status small.disabled { color: var(--pi-warning); }
1554
+ .shortcut-status small.conflict { border: 1px solid currentColor; border-radius: 999px; padding: 2px 7px; }
1555
+ .shortcut-status small.conflict.shadowing { color: var(--pi-accent); }
1556
+ .shortcut-status small.conflict.shadowed { color: var(--pi-warning); }
1557
+ .shortcut-input-label { min-width: 0; display: grid; gap: 5px; }
1558
+ .shortcut-input-label span { color: var(--pi-muted); font-size: 11px; font-weight: 700; text-transform: uppercase; }
1559
+ input { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 8px 9px; outline: none; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1560
+ input:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1561
+ .shortcut-actions { display: flex; justify-content: flex-end; gap: 7px; flex-wrap: wrap; }
1562
+ kbd { 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; }
1563
+ .unassigned { color: var(--pi-muted); font-size: 12px; }
1564
+ .recording-hint { color: var(--pi-accent); font-size: 12px; }
1565
+
1566
+ @media (max-width: 760px) {
1567
+ .section-heading { display: grid; gap: 12px; }
1568
+ .section-heading .secondary { justify-self: start; }
1569
+ .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1570
+ .shortcut-status, .shortcut-actions { justify-content: flex-start; }
1571
+ }
1572
+ `;be([d({attribute:!1})],se.prototype,"actions",2);be([d({attribute:!1})],se.prototype,"configResponse",2);be([d({type:Boolean})],se.prototype,"loading",2);be([d({type:Boolean})],se.prototype,"saving",2);be([d()],se.prototype,"error",2);be([d()],se.prototype,"savedMessage",2);be([d({attribute:!1})],se.prototype,"onReload",2);be([d({attribute:!1})],se.prototype,"onSave",2);be([b()],se.prototype,"drafts",2);be([b()],se.prototype,"localError",2);be([b()],se.prototype,"recording",2);se=be([E("settings-shortcuts-panel")],se);function vv(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function bv(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function wv(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(o=>o.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function yv(e){const t=new Map;for(const i of[...e].sort(Sv)){const s=i.group??"Other";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function Sv(e,t){return(e.group??"Other").localeCompare(t.group??"Other")||e.title.localeCompare(t.title)}function xi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function xv(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function kv(e,t){const i=xi(e.id,t);if(i!==null)return i??e.shortcut}function $v(e,t){const i=xi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function Pv(e){switch(e){case"default":return"Default";case"custom":return"Custom";case"disabled":return"Disabled";case"unassigned":return"No default"}}function Rv(e){return e.target instanceof HTMLInputElement?e.target.value:""}var Cv=Object.defineProperty,Iv=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var o=s>1?void 0:s?Iv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Cv(t,i,o),o};let oe=class extends C{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`
1573
+ <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1574
+ <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1575
+ <header class="settings-header">
1576
+ <div>
1577
+ <span class="eyebrow">Settings</span>
1578
+ <h1>PI WEB</h1>
1579
+ </div>
1580
+ <button class="close-button" title="Close settings" aria-label="Close settings" @click=${()=>this.onClose?.()}>×</button>
1581
+ </header>
1582
+ <div class="settings-body">
1583
+ <nav class="settings-nav" aria-label="Settings sections">
1584
+ ${this.renderNavButton("general","General","Server config")}
1585
+ ${this.renderNavButton("plugins","Plugins","Enable and disable")}
1586
+ ${this.renderNavButton("shortcuts","Keyboard","Shortcuts")}
1587
+ </nav>
1588
+ <main class="settings-content">
1589
+ ${this.renderActiveSection()}
1590
+ </main>
1591
+ </div>
1592
+ </section>
1593
+ </div>
1594
+ `}renderActiveSection(){return this.section==="shortcuts"?l`
1595
+ <settings-shortcuts-panel
1596
+ .actions=${this.actions}
1597
+ .configResponse=${this.configResponse}
1598
+ .loading=${this.loading}
1599
+ .saving=${this.saving}
1600
+ .error=${this.error}
1601
+ .savedMessage=${this.savedMessage}
1602
+ .onReload=${()=>this.loadConfig()}
1603
+ .onSave=${e=>this.saveConfig(e)}
1604
+ ></settings-shortcuts-panel>
1605
+ `:this.section==="plugins"?l`
1606
+ <settings-plugins-panel
1607
+ .configResponse=${this.configResponse}
1608
+ .pluginsResponse=${this.pluginsResponse}
1609
+ .loading=${this.loading}
1610
+ .saving=${this.saving}
1611
+ .error=${this.error}
1612
+ .savedMessage=${this.savedMessage}
1613
+ .onReload=${()=>this.loadConfig()}
1614
+ .onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
1615
+ ></settings-plugins-panel>
1616
+ `:l`
1617
+ <settings-general-panel
1618
+ .configResponse=${this.configResponse}
1619
+ .loading=${this.loading}
1620
+ .saving=${this.saving}
1621
+ .error=${this.error}
1622
+ .savedMessage=${this.savedMessage}
1623
+ .onReload=${()=>this.loadConfig()}
1624
+ .onSave=${e=>this.saveConfig(e)}
1625
+ ></settings-general-panel>
1626
+ `}renderNavButton(e,t,i){const s=this.section===e;return l`
1627
+ <button class=${s?"selected":""} aria-current=${s?"page":"false"} @click=${()=>{this.navigate(e)}}>
1628
+ <strong>${t}</strong>
1629
+ <small>${i}</small>
1630
+ </button>
1631
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([ai.config(),hs.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`Failed to load settings: ${os(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},o=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...o,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await ai.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`Failed to save config: ${os(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await hs.plugins()}catch(e){this.error=`Failed to refresh plugins: ${os(e)}`}}showSavedMessage(){this.savedMessage="Config saved.",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="Config saved."&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};oe.styles=W`
1632
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1633
+ .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; }
1634
+ .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; }
1635
+ .settings-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
1636
+ .eyebrow { display: block; color: var(--pi-muted); font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
1637
+ h1 { margin: 0; font-size: 20px; line-height: 1.2; }
1638
+ 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; }
1639
+ .close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
1640
+ .close-button:hover, .close-button:focus { color: var(--pi-text); background: var(--pi-surface-hover); }
1641
+ .settings-body { min-height: 0; display: grid; grid-template-columns: 220px minmax(0, 1fr); }
1642
+ .settings-nav { min-height: 0; padding: 10px; border-right: 1px solid var(--pi-border); background: var(--pi-surface); overflow: auto; }
1643
+ .settings-nav button { display: grid; gap: 2px; width: 100%; margin: 0 0 6px; text-align: left; border-color: transparent; background: transparent; }
1644
+ .settings-nav button:hover, .settings-nav button:focus { background: var(--pi-surface-hover); }
1645
+ .settings-nav button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1646
+ .settings-nav small { color: var(--pi-muted); }
1647
+ .settings-content { min-width: 0; min-height: 0; overflow: auto; padding: 18px; }
1648
+
1649
+ @media (max-width: 760px) {
1650
+ .backdrop { padding: 0; place-items: stretch; }
1651
+ .settings-shell { width: 100%; height: 100dvh; max-height: none; min-height: 0; border: 0; border-radius: 0; }
1652
+ .settings-header { padding: max(12px, env(safe-area-inset-top)) 12px 12px; }
1653
+ .settings-body { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
1654
+ .settings-nav { display: flex; gap: 8px; padding: 8px; border-right: 0; border-bottom: 1px solid var(--pi-border); overflow-x: auto; overflow-y: hidden; }
1655
+ .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
1656
+ .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
1657
+ }
1658
+ `;we([d({attribute:!1})],oe.prototype,"section",2);we([d({attribute:!1})],oe.prototype,"actions",2);we([d({attribute:!1})],oe.prototype,"onNavigate",2);we([d({attribute:!1})],oe.prototype,"onClose",2);we([d({attribute:!1})],oe.prototype,"onConfigSaved",2);we([b()],oe.prototype,"configResponse",2);we([b()],oe.prototype,"pluginsResponse",2);we([b()],oe.prototype,"loading",2);we([b()],oe.prototype,"saving",2);we([b()],oe.prototype,"error",2);we([b()],oe.prototype,"savedMessage",2);oe=we([E("settings-dialog")],oe);function os(e){return e instanceof Error?e.message:String(e)}var Mv=Object.defineProperty,Tv=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?Tv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Mv(t,i,o),o};let le=class extends C{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"Select a workspace",body:"Choose a workspace to inspect files, Git, or terminals."});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"Workspace tools unavailable",body:"Try selecting the workspace again."});const i=this.panels,s=i.find(o=>o.id===this.tool)??i[0];return l`
1659
+ ${this.hideToolTabs?null:l`
1660
+ <header>
1661
+ <div class=${this.workspaceHeaderFrameClass()}>
1662
+ <div class="workspace-header-strip" @scroll=${this.onWorkspaceHeaderScroll}>
1663
+ <div class="tabs">
1664
+ ${i.map(o=>{const r=s?.id===o.id,n=o.badge?.(t),a=this.panelTabAriaLabel(o,n);return l`
1665
+ <button class=${this.panelTabClass(o,r)} title=${a} aria-label=${a} aria-pressed=${String(r)} @click=${()=>{this.onSelectTool(o.id)}}>
1666
+ ${this.renderPanelTabContent(o,n)}
1667
+ </button>
1668
+ `})}
1669
+ </div>
1670
+ </div>
1671
+ </div>
1672
+ </header>
1673
+ `}
1674
+ ${s===void 0?this.renderEmptyState({title:"No workspace tools available",body:"No tools are available for this workspace."}):l`
1675
+ <div class="panel-content">
1676
+ ${s.render(t)}
1677
+ </div>
1678
+ `}
1679
+ `}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`
1680
+ ${e.icon===void 0?null:l`<span class="tab-custom-icon" aria-hidden="true">${e.icon}</span>`}
1681
+ <span class="tab-label">${e.title}</span>
1682
+ ${this.isEmptyBadge(t)?null:l`<span class="tab-badge">${t}</span>`}
1683
+ `}isEmptyBadge(e){return e===void 0||e===""}renderEmptyState(e){return l`
1684
+ <section class="empty-state" role="status">
1685
+ <h2>${e.title}</h2>
1686
+ ${e.body===void 0?null:l`<p>${e.body}</p>`}
1687
+ </section>
1688
+ `}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}};le.styles=gf;Ce([d({attribute:!1})],le.prototype,"workspace",2);Ce([d({attribute:!1})],le.prototype,"panelContext",2);Ce([d({attribute:!1})],le.prototype,"emptyState",2);Ce([d()],le.prototype,"tool",2);Ce([d({attribute:!1})],le.prototype,"panels",2);Ce([d({type:Boolean})],le.prototype,"hideToolTabs",2);Ce([d({attribute:!1})],le.prototype,"onSelectTool",2);Ce([z(".workspace-header-strip")],le.prototype,"workspaceHeaderStrip",2);Ce([b()],le.prototype,"workspaceHeaderCanScrollLeft",2);Ce([b()],le.prototype,"workspaceHeaderCanScrollRight",2);le=Ce([E("workspace-panel")],le);var Av=Object.defineProperty,Ev=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ev(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Av(t,i,o),o};let re=class extends C{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=Dv(this.machines),t=Wv(this.machine),i=Ov(this.project),s=jv(this.workspace),o=zv(this.session);return l`
1689
+ <nav class=${this.contextBarClass()} aria-label="Current location">
1690
+ <span class="context-bar-label">Location</span>
1691
+ <ol class="context-items" @scroll=${this.onContextScroll}>
1692
+ ${e?l`
1693
+ <li class="context-item">
1694
+ <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${_v(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.("machines")}}>
1695
+ <span class="context-kind">Machine</span>
1696
+ <span class="context-value">${t}</span>
1697
+ </button>
1698
+ </li>
1699
+ `:null}
1700
+ <li class="context-item">
1701
+ <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${Lv(this.project)} aria-label=${`Project: ${i}. Open project selection.`} @click=${()=>{this.onOpenSection?.("projects")}}>
1702
+ <span class="context-kind">Project</span>
1703
+ <span class="context-value">${i}</span>
1704
+ </button>
1705
+ </li>
1706
+ <li class="context-item">
1707
+ <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${Nv(this.workspace)} aria-label=${`Workspace: ${s}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1708
+ <span class="context-kind">Workspace</span>
1709
+ <span class="context-value">${s}</span>
1710
+ </button>
1711
+ </li>
1712
+ <li class="context-item">
1713
+ <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${Fv(this.session)} aria-label=${`Session: ${o}. Open session selection.`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1714
+ <span class="context-kind">Session</span>
1715
+ <span class="context-value">${o}</span>
1716
+ </button>
1717
+ </li>
1718
+ </ol>
1719
+ ${this.hasContextActions()?l`<div class="context-actions">${this.renderActionsButton()}${this.refreshControl}</div>`:null}
1720
+ </nav>
1721
+ `}renderActionsButton(){return this.onShowActions===void 0?null:l`
1722
+ <button type="button" class="context-action-button" title="Show Actions" aria-label="Show Actions" @click=${e=>{e.stopPropagation(),this.onShowActions?.()}}>
1723
+ <svg class="context-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1724
+ <path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
1725
+ </svg>
1726
+ </button>
1727
+ `}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}};re.styles=W`
1728
+ /* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
1729
+ :host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
1730
+ .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); }
1731
+ .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; }
1732
+ .context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1733
+ .context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1734
+ .context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
1735
+ .context-bar-label { display: none; }
1736
+ .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; }
1737
+ .context-bar.has-context-actions .context-items { padding-right: 58px; scroll-padding-inline: 8px 58px; }
1738
+ .context-bar.has-context-actions-double .context-items { padding-right: 102px; scroll-padding-inline: 8px 102px; }
1739
+ .context-item { flex: 0 0 auto; min-width: 0; display: flex; }
1740
+ .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; }
1741
+ .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; }
1742
+ app-refresh-control, .context-action-button { position: relative; z-index: 1; pointer-events: auto; }
1743
+ .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; }
1744
+ .context-action-button:hover, .context-action-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1745
+ .context-action-icon { width: 18px; height: 18px; fill: currentColor; pointer-events: none; }
1746
+ .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; }
1747
+ .context-chip:hover { background: var(--pi-surface-hover); }
1748
+ .context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
1749
+ .context-chip.empty { border-style: dashed; color: var(--pi-muted); }
1750
+ .context-kind { display: none; }
1751
+ .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
1752
+ button { cursor: pointer; }
1753
+ `;ye([d({attribute:!1})],re.prototype,"machines",2);ye([d({attribute:!1})],re.prototype,"machine",2);ye([d({attribute:!1})],re.prototype,"project",2);ye([d({attribute:!1})],re.prototype,"workspace",2);ye([d({attribute:!1})],re.prototype,"session",2);ye([d({attribute:!1})],re.prototype,"refreshControl",2);ye([d({attribute:!1})],re.prototype,"onOpenSection",2);ye([d({attribute:!1})],re.prototype,"onShowActions",2);ye([z(".context-items")],re.prototype,"contextItems",2);ye([b()],re.prototype,"canScrollLeft",2);ye([b()],re.prototype,"canScrollRight",2);re=ye([E("app-context-bar")],re);function Dv(e){return e.length>1}function Wv(e){return e===void 0?"No machine":`${e.name}${e.kind==="remote"?" · remote":""}`}function _v(e){return e===void 0?"No machine selected":e.baseUrl??e.name}function Ov(e){return e?.name??"No project"}function Lv(e){return e===void 0?"No project selected":`${e.name} — ${e.path}`}function jv(e){return e===void 0?"No workspace":`${e.label}${e.isMain?" · main":""} · ${e.path}`}function Nv(e){return e===void 0?"No workspace selected":`${e.label}${e.isMain?" · main":""} — ${e.path}`}function zv(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)??"No session"}function Fv(e){return e===void 0?"No session selected":e.path}var Bv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,Ye=(e,t,i,s)=>{for(var o=s>1?void 0:s?Uv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Bv(t,i,o),o};let Oe=class extends C{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`
1754
+ <div class=${this.frameClass()}>
1755
+ <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
1756
+ ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
1757
+ <button class=${this.tabClass(t)} title=${t.label} aria-label=${this.tabAriaLabel(t)} aria-pressed=${String(i)} @click=${()=>{this.onSelect?.(t.id)}}>
1758
+ ${this.renderTabMark(t,e)}
1759
+ <span class="tab-label">${t.label}</span>
1760
+ ${this.isEmptyBadge(t.badge)?null:l`<span class="tab-badge">${t.badge}</span>`}
1761
+ </button>
1762
+ `})}
1763
+ </div>
1764
+ </div>
1765
+ `}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>`:Dh(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const o=this.initialsLabel(s.label);t.set(o,(t.get(o)??0)+1)}const i=new Map;for(const s of e){const o=this.initialsLabel(s.label);i.set(s.id,(t.get(o)??0)>1?this.fullFallbackLabel(s.label):o)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};Oe.styles=W`
1766
+ :host { flex: 0 0 auto; min-width: 0; }
1767
+ .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); }
1768
+ .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; }
1769
+ .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1770
+ .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1771
+ .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
1772
+ .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; }
1773
+ .mobile-tabs button { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
1774
+ .mobile-tabs .navigation-tab { display: none; }
1775
+ .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1776
+ .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; }
1777
+ .tab-custom-icon { flex: 0 0 auto; width: 18px; height: 18px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
1778
+ .tab-custom-icon svg { width: 18px; height: 18px; pointer-events: none; }
1779
+ .tab-fallback { display: none; font-weight: 650; letter-spacing: .01em; pointer-events: none; }
1780
+ .tab-label { min-width: 0; }
1781
+ .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; }
1782
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1783
+ @media (max-width: 760px) {
1784
+ .mobile-tabs { gap: 4px; padding: 6px 8px; }
1785
+ .mobile-tabs button { min-width: 40px; height: 36px; justify-content: center; gap: 4px; padding: 0 8px; }
1786
+ .mobile-tabs .navigation-tab { display: inline-flex; }
1787
+ .tab-fallback { display: inline-block; }
1788
+ .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; }
1789
+ .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
1790
+ }
1791
+ `;Ye([d({attribute:!1})],Oe.prototype,"tabs",2);Ye([d({attribute:!1})],Oe.prototype,"selectedView",2);Ye([d({attribute:!1})],Oe.prototype,"onSelect",2);Ye([z(".mobile-tabs")],Oe.prototype,"mobileTabs",2);Ye([b()],Oe.prototype,"canScrollLeft",2);Ye([b()],Oe.prototype,"canScrollRight",2);Oe=Ye([E("app-mobile-main-tabs")],Oe);var Hv=Object.defineProperty,qv=Object.getOwnPropertyDescriptor,de=(e,t,i,s)=>{for(var o=s>1?void 0:s?qv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hv(t,i,o),o};let Y=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=rs(e,this.statuses),i=e.name;return l`
1792
+ <div class="machine-switcher">
1793
+ <button
1794
+ type="button"
1795
+ class="machine-switcher-button"
1796
+ title=${Fr(e)}
1797
+ aria-label=${`Machine: ${i}. Switch machine.`}
1798
+ aria-expanded=${String(this.open)}
1799
+ @click=${s=>{this.toggleMenu(s.currentTarget)}}
1800
+ @keydown=${s=>{this.handleSwitcherButtonKeydown(s)}}
1801
+ >
1802
+ ${this.renderActivity(e)}
1803
+ <span class="machine-switcher-text">
1804
+ <span class="machine-switcher-kicker">Machine</span>
1805
+ <span class="machine-switcher-label">${i}</span>
1806
+ </span>
1807
+ <span class=${`machine-status ${t}`}>${zr(t)}</span>
1808
+ <span class="machine-chevron" aria-hidden="true">▾</span>
1809
+ </button>
1810
+ ${this.open?l`
1811
+ <div class="machine-switcher-menu" style=${this.menuStyle} @click=${s=>{s.stopPropagation()}}>
1812
+ ${this.machines.map(s=>this.renderMachineOption(s))}
1813
+ </div>
1814
+ `:null}
1815
+ </div>
1816
+ `}renderMachineOption(e){const t=this.selected?.id===e.id,i=rs(e,this.statuses),s=ea(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return l`
1817
+ <div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
1818
+ <button
1819
+ type="button"
1820
+ class="machine-option-main"
1821
+ title=${Fr(e)}
1822
+ data-machine-id=${e.id}
1823
+ @click=${()=>{this.select(e)}}
1824
+ @keydown=${r=>{this.handleMachineOptionKeydown(r)}}
1825
+ >
1826
+ <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
1827
+ <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${zr(i)}</small>
1828
+ </button>
1829
+ ${s?l`
1830
+ <div class="machine-option-actions">
1831
+ <button
1832
+ type="button"
1833
+ class="machine-option-actions-toggle"
1834
+ title="Machine actions"
1835
+ aria-label=${`Actions for ${e.name}`}
1836
+ aria-expanded=${String(o)}
1837
+ @click=${r=>{r.stopPropagation(),this.toggleActionsMenu(e.id,r.currentTarget)}}
1838
+ >⋯</button>
1839
+ ${o?l`
1840
+ <div class="machine-option-actions-panel" style=${this.actionMenuStyle} @click=${r=>{r.stopPropagation()}}>
1841
+ <button class="danger" title=${`Remove ${e.name}`} @click=${()=>{this.removeMachine(e)}}>Remove</button>
1842
+ </div>
1843
+ `:null}
1844
+ </div>
1845
+ `:null}
1846
+ </div>
1847
+ `}renderActivity(e){const t=rs(e,this.statuses);if(t==="offline"||t==="error")return;const i=qn(this.activities[e.id]);return Gn(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}switcherButton(){return this.renderRoot.querySelector(".machine-switcher-button")}handleSwitcherButtonKeydown(e){if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key==="Escape"&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key==="ArrowUp"){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key==="ArrowDown"){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key==="Home"){this.focusIndexedMachineOption(0,e);return}if(e.key==="End"){this.focusIndexedMachineOption(-1,e);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key==="ArrowLeft"||e.key==="Escape")&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=Br(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){const e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=Br(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const o=s.indexOf(e);o<0||this.focusMachineOptionAt(o+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=jt(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};Y.styles=W`
1848
+ :host { min-width: 0; display: block; }
1849
+ .machine-switcher { min-width: 0; }
1850
+ .machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
1851
+ .machine-switcher-button:hover, .machine-switcher-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1852
+ .machine-switcher-text { flex: 1 1 auto; min-width: 0; display: grid; gap: 1px; }
1853
+ .machine-switcher-kicker { color: var(--pi-muted); font-size: 10px; line-height: 1; text-transform: uppercase; letter-spacing: .02em; }
1854
+ .machine-switcher-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 600; line-height: 1.2; }
1855
+ .machine-status { flex: 0 0 auto; color: var(--pi-muted); font-size: 11px; }
1856
+ .machine-status.online { color: var(--pi-success); }
1857
+ .machine-status.offline, .machine-status.error { color: var(--pi-danger); }
1858
+ .machine-chevron { flex: 0 0 auto; color: var(--pi-muted); font-size: 11px; }
1859
+ .activity-indicator { flex: 0 0 auto; display: inline-block; width: 7px; height: 7px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; }
1860
+ .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
1861
+ .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
1862
+ .machine-switcher-menu { position: fixed; z-index: 10000; box-sizing: border-box; min-width: min(280px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); }
1863
+ .machine-option { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px; align-items: stretch; margin: 2px 0; }
1864
+ .machine-option.no-actions { grid-template-columns: minmax(0, 1fr); }
1865
+ .machine-option-main, .machine-option-actions-toggle, .machine-option-actions-panel button { border: 0; border-radius: 7px; background: transparent; color: var(--pi-text); cursor: pointer; }
1866
+ .machine-option-main { min-width: 0; display: grid; gap: 2px; padding: 7px 8px; text-align: left; }
1867
+ .machine-option-name { min-width: 0; display: flex; align-items: baseline; gap: 6px; }
1868
+ .machine-option-name span:last-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1869
+ .machine-option-main small { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-muted); }
1870
+ .machine-option-actions { position: relative; align-self: stretch; }
1871
+ .machine-option-actions-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); }
1872
+ .machine-option-actions-panel { position: fixed; z-index: 10001; 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); }
1873
+ .machine-option-actions-panel button { display: block; width: 100%; padding: 7px 9px; text-align: left; white-space: nowrap; }
1874
+ .machine-option-actions-panel button.danger { color: var(--pi-danger); }
1875
+ .machine-option-main:hover, .machine-option-main:focus-visible, .machine-option-actions-toggle:hover, .machine-option-actions-toggle:focus-visible, .machine-option.selected .machine-option-main { background: var(--pi-selection-bg); }
1876
+ .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
1877
+ .machine-option-actions-panel button.danger:hover, .machine-option-actions-panel button.danger:focus-visible { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
1878
+ @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
1879
+ `;de([d({attribute:!1})],Y.prototype,"machines",2);de([d({attribute:!1})],Y.prototype,"selected",2);de([d({attribute:!1})],Y.prototype,"statuses",2);de([d({attribute:!1})],Y.prototype,"activities",2);de([d({attribute:!1})],Y.prototype,"onSelect",2);de([d({attribute:!1})],Y.prototype,"onRemove",2);de([d({attribute:!1})],Y.prototype,"onFocusNextSection",2);de([d({attribute:!1})],Y.prototype,"onCancelKeyboardNavigation",2);de([b()],Y.prototype,"open",2);de([b()],Y.prototype,"menuStyle",2);de([b()],Y.prototype,"openActionsMachineId",2);de([b()],Y.prototype,"actionMenuStyle",2);Y=de([E("machine-switcher")],Y);function rs(e,t){return t[e.id]?.status??e.status??"unknown"}function zr(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function Fr(e){return e.baseUrl??e.name}function Br(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),o=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),r=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${Gt(t.bottom)};`,`left: ${Gt(o)};`,`width: ${Gt(s)};`,`max-height: ${Gt(r)};`].join(" ")}function Gt(e){return`${String(Math.round(e))}px`}var Kv=Object.defineProperty,Vv=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var o=s>1?void 0:s?Vv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Kv(t,i,o),o};let x=class extends C{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.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
1880
+ <header>
1881
+ <strong>PI WEB</strong>
1882
+ ${ki(this.machines)?l`
1883
+ <machine-switcher
1884
+ .machines=${this.machines}
1885
+ .selected=${this.selectedMachine}
1886
+ .statuses=${this.machineStatuses}
1887
+ .activities=${this.machineActivities}
1888
+ .onSelect=${e=>this.onSelectMachine?.(e)}
1889
+ .onRemove=${e=>this.onRemoveMachine?.(e)}
1890
+ .onFocusNextSection=${()=>{this.focusNextFrom("machines")}}
1891
+ .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
1892
+ ></machine-switcher>
1893
+ `:null}
1894
+ <div class="header-actions">
1895
+ ${this.refreshControl}
1896
+ <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
1897
+ </div>
1898
+ </header>
1899
+ ${this.compact&&ki(this.machines)?l`
1900
+ <machine-list
1901
+ .machines=${this.machines}
1902
+ .selected=${this.selectedMachine}
1903
+ .statuses=${this.machineStatuses}
1904
+ .activities=${this.machineActivities}
1905
+ .collapsible=${this.collapsible}
1906
+ .collapsed=${this.machinesCollapsed}
1907
+ .onToggleCollapsed=${()=>{this.onToggleMachines?.()}}
1908
+ .onSelect=${e=>this.onSelectMachine?.(e)}
1909
+ .onRemove=${e=>this.onRemoveMachine?.(e)}
1910
+ .onFocusNextSection=${()=>{this.focusNextFrom("machines")}}
1911
+ .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
1912
+ ></machine-list>
1913
+ `:null}
1914
+ <project-list
1915
+ .projects=${this.projects}
1916
+ .selected=${this.selectedProject}
1917
+ .activities=${this.workspaceActivities}
1918
+ .workspacesByProjectId=${this.workspacesByProjectId}
1919
+ .collapsible=${this.collapsible}
1920
+ .collapsed=${this.projectsCollapsed}
1921
+ .onToggleCollapsed=${()=>{this.onToggleProjects?.()}}
1922
+ .onSelect=${e=>this.onSelectProject?.(e)}
1923
+ .onClose=${e=>this.onCloseProject?.(e)}
1924
+ .onFocusPreviousSection=${()=>{this.focusPreviousFrom("projects")}}
1925
+ .onFocusNextSection=${()=>{this.focusNextFrom("projects")}}
1926
+ .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
1927
+ ></project-list>
1928
+ <workspace-list
1929
+ .workspaces=${this.workspaces}
1930
+ .selected=${this.selectedWorkspace}
1931
+ .activities=${this.workspaceActivities}
1932
+ .deletingWorkspaceIds=${this.deletingWorkspaceIds}
1933
+ .collapsible=${this.collapsible}
1934
+ .collapsed=${this.workspacesCollapsed}
1935
+ .workspaceLabelItems=${this.workspaceLabelItems}
1936
+ .onToggleCollapsed=${()=>{this.onToggleWorkspaces?.()}}
1937
+ .onSelect=${e=>this.onSelectWorkspace?.(e)}
1938
+ .onDelete=${e=>this.onDeleteWorkspace?.(e)}
1939
+ .onFocusPreviousSection=${()=>{this.focusPreviousFrom("workspaces")}}
1940
+ .onFocusNextSection=${()=>{this.focusNextFrom("workspaces")}}
1941
+ .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
1942
+ ></workspace-list>
1943
+ <session-list
1944
+ .sessions=${this.sessions}
1945
+ .statuses=${this.sessionStatuses}
1946
+ .activities=${this.sessionActivities}
1947
+ .selected=${this.selectedSession}
1948
+ .canStart=${this.canStartSession}
1949
+ .canDeleteArchived=${this.canDeleteArchivedSessions}
1950
+ .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage}
1951
+ .collapsible=${this.collapsible}
1952
+ .collapsed=${this.sessionsCollapsed}
1953
+ .onToggleCollapsed=${()=>{this.onToggleSessions?.()}}
1954
+ .onArchivedCollapsed=${()=>this.onArchivedCollapsed?.()}
1955
+ .onStart=${()=>this.onStartSession?.()}
1956
+ .onSelect=${e=>this.onSelectSession?.(e)}
1957
+ .onArchive=${e=>this.onArchiveSession?.(e)}
1958
+ .onArchiveWithDescendants=${e=>this.onArchiveSessionWithDescendants?.(e)}
1959
+ .onArchiveMany=${e=>this.onArchiveSessions?.(e)}
1960
+ .onRestore=${e=>this.onRestoreSession?.(e)}
1961
+ .onDelete=${e=>this.onDeleteCachedNewSession?.(e)}
1962
+ .onDeleteArchived=${e=>this.onDeleteArchivedSession?.(e)}
1963
+ .onDeleteArchivedMany=${e=>this.onDeleteArchivedSessions?.(e)}
1964
+ .onDetachParent=${e=>this.onDetachParentSession?.(e)}
1965
+ .onFocusPreviousSection=${()=>{this.focusPreviousFrom("sessions")}}
1966
+ .onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
1967
+ .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
1968
+ ></session-list>
1969
+ `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=Gv(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Qv(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=W`
1970
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
1971
+ :host([compact]) { flex: 1 1 auto; }
1972
+ 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); }
1973
+ header strong { flex: 0 0 auto; }
1974
+ machine-switcher { flex: 1 1 auto; min-width: 0; }
1975
+ :host([compact]) header { display: none; }
1976
+ .header-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; }
1977
+ 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); }
1978
+ session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
1979
+ machine-list[collapsed],
1980
+ project-list[collapsed],
1981
+ workspace-list[collapsed],
1982
+ session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
1983
+ :host([compact]) machine-list,
1984
+ :host([compact]) project-list,
1985
+ :host([compact]) workspace-list,
1986
+ :host([compact]) session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
1987
+ :host([compact]) machine-list[collapsed],
1988
+ :host([compact]) project-list[collapsed],
1989
+ :host([compact]) workspace-list[collapsed],
1990
+ :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
1991
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1992
+ `;k([d({attribute:!1})],x.prototype,"machines",2);k([d({attribute:!1})],x.prototype,"selectedMachine",2);k([d({attribute:!1})],x.prototype,"machineStatuses",2);k([d({attribute:!1})],x.prototype,"machineActivities",2);k([d({attribute:!1})],x.prototype,"projects",2);k([d({attribute:!1})],x.prototype,"selectedProject",2);k([d({attribute:!1})],x.prototype,"workspaces",2);k([d({attribute:!1})],x.prototype,"selectedWorkspace",2);k([d({attribute:!1})],x.prototype,"sessions",2);k([d({attribute:!1})],x.prototype,"selectedSession",2);k([d({attribute:!1})],x.prototype,"workspaceActivities",2);k([d({attribute:!1})],x.prototype,"sessionActivities",2);k([d({attribute:!1})],x.prototype,"sessionStatuses",2);k([d({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],x.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([d({type:Boolean})],x.prototype,"machinesCollapsed",2);k([d({type:Boolean})],x.prototype,"projectsCollapsed",2);k([d({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],x.prototype,"canStartSession",2);k([d({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([d({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([d({attribute:!1})],x.prototype,"onShowActions",2);k([d({attribute:!1})],x.prototype,"onToggleMachines",2);k([d({attribute:!1})],x.prototype,"onToggleProjects",2);k([d({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],x.prototype,"onToggleSessions",2);k([d({attribute:!1})],x.prototype,"onSelectProject",2);k([d({attribute:!1})],x.prototype,"onCloseProject",2);k([d({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],x.prototype,"onStartSession",2);k([d({attribute:!1})],x.prototype,"onSelectSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],x.prototype,"onArchiveSessions",2);k([d({attribute:!1})],x.prototype,"onRestoreSession",2);k([d({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],x.prototype,"onDetachParentSession",2);k([d({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],x.prototype,"onSelectMachine",2);k([d({attribute:!1})],x.prototype,"onRemoveMachine",2);k([d({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([z("machine-list")],x.prototype,"machineList",2);k([z("machine-switcher")],x.prototype,"machineSwitcher",2);k([z("project-list")],x.prototype,"projectList",2);k([z("workspace-list")],x.prototype,"workspaceList",2);k([z("session-list")],x.prototype,"sessionList",2);x=k([E("app-navigation-panel")],x);function ki(e){return e.length>1}function Gv(e,t){const i=wa(t);return i[i.indexOf(e)-1]}function Qv(e,t){const i=wa(t);return i[i.indexOf(e)+1]??"chat"}function wa(e){return mi.filter(t=>t!=="machines"||ki(e))}var Zv=Object.defineProperty,Jv=Object.getOwnPropertyDescriptor,J=(e,t,i,s)=>{for(var o=s>1?void 0:s?Jv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Zv(t,i,o),o};const Xv=new Set(["ArrowLeft","ArrowRight","Home","End"]),Yv=420,eb=4;let q=class extends C{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="Resize panel",this.expandLabel="Expand panel",this.collapseLabel="Collapse panel",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
1993
+ ${this.renderResizeHandle()}
1994
+ <button
1995
+ type="button"
1996
+ class="edge-button"
1997
+ title=${e}
1998
+ aria-label=${e}
1999
+ aria-controls=${this.controls}
2000
+ aria-expanded=${String(!this.collapsed)}
2001
+ @click=${()=>{this.onToggle?.()}}
2002
+ >${this.renderIcon()}</button>
2003
+ `}renderResizeHandle(){if(!this.resizable)return L;const e=this.resizeConstraints();return l`
2004
+ <div
2005
+ class="resize-handle"
2006
+ role="separator"
2007
+ tabindex="0"
2008
+ aria-label=${this.resizeLabel}
2009
+ title=${`${this.resizeLabel}. Double-click or double-tap to reset.`}
2010
+ aria-controls=${this.controls}
2011
+ aria-orientation="vertical"
2012
+ aria-valuemin=${String(e.minWidth)}
2013
+ aria-valuemax=${String(e.maxWidth)}
2014
+ aria-valuenow=${this.resizeAriaValueNow()}
2015
+ @pointerdown=${t=>{this.onResizePointerDown(t)}}
2016
+ @pointermove=${t=>{this.onResizePointerMove(t)}}
2017
+ @pointerup=${t=>{this.onResizePointerUp(t)}}
2018
+ @pointercancel=${t=>{this.onResizePointerCancel(t)}}
2019
+ @dblclick=${t=>{this.onResizeDoubleClick(t)}}
2020
+ @keydown=${t=>{this.onResizeKeyDown(t)}}
2021
+ ></div>
2022
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?L:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=eb)&&(t.moved=!0,this.commitPanelWidth(Nu(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!Xv.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=zu(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});i!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(i),this.onResizeEnd?.())}registerTapForReset(){const e=Date.now();if(e-this.lastTapAt<=Yv){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return he(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(he(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=Lt(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};q.styles=W`
2023
+ :host { position: relative; min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
2024
+ :host([side="navigation"]) { grid-column: 2; }
2025
+ :host([side="workspace"]) { grid-column: 4; }
2026
+ .resize-handle { position: absolute; inset: 0 -6px; z-index: 0; cursor: col-resize; touch-action: none; outline: none; }
2027
+ .resize-handle::after { content: ""; position: absolute; top: 0; bottom: 0; left: 50%; width: 1px; transform: translateX(-50%); background: transparent; transition: width .12s ease, background .12s ease, opacity .12s ease; }
2028
+ .resize-handle:hover::after, .resize-handle:focus-visible::after, :host([resizing]) .resize-handle::after { width: 3px; background: var(--pi-accent); opacity: .72; }
2029
+ .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; }
2030
+ .edge-button:hover, .edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
2031
+ :host([side="navigation"][collapsed]) .edge-button { transform: translateX(calc(50% - .5px)); }
2032
+ :host([side="workspace"][collapsed]) .edge-button { transform: translateX(calc(-50% + .5px)); }
2033
+ .edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2034
+ @media (max-width: 1180px) {
2035
+ :host([side="navigation"]) { grid-row: 1 / 3; }
2036
+ :host([side="workspace"]) { display: none; }
2037
+ }
2038
+ @media (max-width: 760px) {
2039
+ :host([side="navigation"]) { display: none; }
2040
+ }
2041
+ `;J([d({reflect:!0})],q.prototype,"side",2);J([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);J([d({type:Boolean})],q.prototype,"resizable",2);J([d({type:Number})],q.prototype,"panelWidth",2);J([d({type:Number})],q.prototype,"minWidth",2);J([d({type:Number})],q.prototype,"maxWidth",2);J([d()],q.prototype,"controls",2);J([d()],q.prototype,"resizeLabel",2);J([d()],q.prototype,"expandLabel",2);J([d()],q.prototype,"collapseLabel",2);J([d({attribute:!1})],q.prototype,"onToggle",2);J([d({attribute:!1})],q.prototype,"onResizeStart",2);J([d({attribute:!1})],q.prototype,"onResize",2);J([d({attribute:!1})],q.prototype,"onResizeEnd",2);J([d({attribute:!1})],q.prototype,"onReset",2);q=J([E("app-panel-edge-control")],q);var tb=Object.defineProperty,ib=Object.getOwnPropertyDescriptor,ya=(e,t,i,s)=>{for(var o=s>1?void 0:s?ib(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&tb(t,i,o),o};let $i=class extends C{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="Full page reload";return l`
2042
+ <button
2043
+ class="app-refresh-button"
2044
+ title=${e}
2045
+ aria-label=${e}
2046
+ @click=${this.onReloadClick}
2047
+ >${this.renderRefreshIcon()}</button>
2048
+ `}renderRefreshIcon(){return l`
2049
+ <svg class="app-refresh-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2050
+ <path d="M20 6v5h-5"></path>
2051
+ <path d="M4 18v-5h5"></path>
2052
+ <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
2053
+ <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
2054
+ </svg>
2055
+ `}};$i.styles=W`
2056
+ :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; }
2057
+ :host, :host * { -webkit-user-select: none; user-select: none; }
2058
+ .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; }
2059
+ .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2060
+ `;ya([d({attribute:!1})],$i.prototype,"onReload",2);$i=ya([E("app-refresh-control")],$i);var sb=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,Ie=(e,t,i,s)=>{for(var o=s>1?void 0:s?ob(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&sb(t,i,o),o};const rb=900*1e3,nb=750,Ms=[1e3,3e3,8e3,15e3,3e4],Ur={capture:!0},ns="auto:on",Hr="auto:off",Qt="theme:",as=Dt("core:workspace.files"),ls=Dt("core:workspace.git"),Zt=Dt("core:workspace.terminal"),ab=320,lb=2,cb="(min-width: 1181px)";let ce=class extends C{constructor(){super(...arguments),this.state=_c(),this.sessions=new xp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new mp),this.activity=new Oc(()=>this.state,e=>{this.setState(e)}),this.auth=new Nc(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Op(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Wp),this.projects=new Gc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Vc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Uc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Kc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Qp,this.realtime=new Qo,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new zp,this.terminalSelection=new Vp,this.appShell=new $u(this),this.panelCollapse=new _u(this),this.panelResize=new Lu(this),this.navigationSections=new Eu(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=db(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=dh()??ah,this.activeThemeId=Zs,this.isRefreshingApp=!1,this.settingsSection=hr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Ur),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},rb),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,Ur),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!ub(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),pb(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=pr();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=this.state.machineStatuses[t.machineId??"local"];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}schedulePiWebStatusRefresh(e=nb){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.refreshPiWebStatus()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshPiWebStatus(){const e=g(this.state);try{const t=await un.piWebStatus(e);g(this.state)===e&&this.setState({piWebStatus:t})}catch(t){g(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=g(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?[g(this.state)]:this.state.machines.filter(t=>Sa(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 ai.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(pr(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=g(this.state),r=e.projectId===void 0||e.projectId===""?Vr():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView: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 c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath: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),g(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?Vr():{selectedFilePath:Ui(as,"file"),selectedDiffPath:Ui(ls,"diff"),selectedTerminalId:Ui(Zt,"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){Qi(e,{replace:!0}),Se(as,"file",void 0,{replace:!0}),Se(ls,"diff",void 0,{replace:!0}),Se(Zt,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=gb(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==""){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=Ms.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",r=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${r===void 0?"":` ${r}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await cs(),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(),Qi({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(Xo(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Xo(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Qi(Yo(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Se(as,"file",e.selectedFilePath,{replace:!0}),Se(ls,"diff",e.selectedDiffPath,{replace:!0}),Se(Zt,"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)??Fp(e.id);if(await this.restoreRouteFor(Yo(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=g(this.state)){const i=Gr(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=ef(e,{api:{runTerminalCommand:(r,n)=>nt.runTerminalCommand(r,n,t),listCommandRuns:r=>nt.listCommandRuns(r,t),getCommandRun:r=>nt.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((g(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"),g(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){Se(Zt,"terminal",e,t)}terminalWorkspaceKey(e){return`${g(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,Zi(e)}closeSettings(){this.settingsSection=void 0,Zi(void 0)}navigateSettings(e){this.settingsSection=e,Zi(e)}restoreSettingsRoute(){this.settingsSection=hr()}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()},g(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new Qo;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=g(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>hb(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):fb(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=g(this.state);try{const i=await nt.terminals(e.projectId,e.id,t);if(g(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=Kr(e),s=Kr(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
2061
+ <workspace-panel
2062
+ id="workspace-panel"
2063
+ .workspace=${e}
2064
+ .panelContext=${t}
2065
+ .emptyState=${i}
2066
+ .tool=${this.state.workspaceTool}
2067
+ .panels=${this.visibleWorkspacePanels()}
2068
+ .onSelectTool=${s=>{this.openWorkspaceTool(s)}}
2069
+ ></workspace-panel>
2070
+ `}renderNavigationPanelEdgeControl(){const e=this.resizablePanelConstraints("navigation");return l`
2071
+ <app-panel-edge-control
2072
+ side="navigation"
2073
+ controls="navigation-panel"
2074
+ resizeLabel="Resize navigation panel"
2075
+ expandLabel="Expand navigation panel"
2076
+ collapseLabel="Collapse navigation panel"
2077
+ .collapsed=${this.panelCollapse.navigationPanelCollapsed}
2078
+ .resizable=${!this.appShell.isMobileNavigationLayout}
2079
+ .panelWidth=${this.panelResize.panelWidth("navigation")}
2080
+ .minWidth=${e.minWidth}
2081
+ .maxWidth=${e.maxWidth}
2082
+ .onToggle=${()=>{this.panelCollapse.toggleNavigationPanel()}}
2083
+ .onResizeStart=${()=>this.startPanelResize("navigation")}
2084
+ .onResize=${t=>{this.panelResize.resizePanel("navigation",t,{persist:!1})}}
2085
+ .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2086
+ .onReset=${()=>{this.resetResizablePanel("navigation")}}
2087
+ ></app-panel-edge-control>
2088
+ `}renderWorkspacePanelEdgeControl(){const e=this.resizablePanelConstraints("workspace");return l`
2089
+ <app-panel-edge-control
2090
+ side="workspace"
2091
+ controls="workspace-panel"
2092
+ resizeLabel="Resize workspace panel"
2093
+ expandLabel="Expand workspace panel"
2094
+ collapseLabel="Collapse workspace panel"
2095
+ .collapsed=${this.panelCollapse.workspacePanelCollapsed}
2096
+ .resizable=${!this.appShell.isMobileNavigationLayout}
2097
+ .panelWidth=${this.panelResize.panelWidth("workspace")}
2098
+ .minWidth=${e.minWidth}
2099
+ .maxWidth=${e.maxWidth}
2100
+ .onToggle=${()=>{this.panelCollapse.toggleWorkspacePanel()}}
2101
+ .onResizeStart=${()=>this.startPanelResize("workspace")}
2102
+ .onResize=${t=>{this.panelResize.resizePanel("workspace",t,{persist:!1})}}
2103
+ .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2104
+ .onReset=${()=>{this.resetResizablePanel("workspace")}}
2105
+ ></app-panel-edge-control>
2106
+ `}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-lb-ab);return Math.max(t.minWidth,Math.min(t.maxWidth,o))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(cb).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&tn(e,Os.sessionsDeleteArchived)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}selectedMachineRuntime(){return this.state.machineRuntimes[g(this.state)]}renderNavigationPanel(){return l`
2107
+ <app-navigation-panel
2108
+ .machines=${this.state.machines}
2109
+ .selectedMachine=${this.state.selectedMachine}
2110
+ .machineStatuses=${this.state.machineStatuses}
2111
+ .machineActivities=${this.state.machineActivities}
2112
+ .machinesCollapsed=${this.navigationSections.isCollapsed("machines")}
2113
+ .onToggleMachines=${()=>{this.navigationSections.toggle("machines")}}
2114
+ .onSelectMachine=${e=>this.selectNavigationItem("machines","projects",()=>this.selectMachineWithMemory(e))}
2115
+ .onRemoveMachine=${e=>{this.removeMachine(e)}}
2116
+ .projects=${this.state.projects}
2117
+ .selectedProject=${this.state.selectedProject}
2118
+ .workspaceActivities=${this.state.workspaceActivities}
2119
+ .workspacesByProjectId=${this.state.workspacesByProjectId}
2120
+ .workspaces=${this.state.workspaces}
2121
+ .selectedWorkspace=${this.state.selectedWorkspace}
2122
+ .deletingWorkspaceIds=${$h(this.state.workspaceDeletionRuns)}
2123
+ .sessions=${this.state.sessions}
2124
+ .sessionStatuses=${this.state.sessionStatuses}
2125
+ .sessionActivities=${this.state.sessionActivities}
2126
+ .selectedSession=${this.state.selectedSession}
2127
+ .canStartSession=${!!this.state.selectedWorkspace}
2128
+ .canDeleteArchivedSessions=${this.canDeleteArchivedSessions()}
2129
+ .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage()}
2130
+ .collapsible=${!0}
2131
+ .compact=${this.appShell.isMobileNavigationLayout}
2132
+ .projectsCollapsed=${this.navigationSections.isCollapsed("projects")}
2133
+ .workspacesCollapsed=${this.navigationSections.isCollapsed("workspaces")}
2134
+ .sessionsCollapsed=${this.navigationSections.isCollapsed("sessions")}
2135
+ .workspaceLabelItems=${e=>this.workspaceLabelItems(e)}
2136
+ .refreshControl=${this.appShell.shouldShowAppRefreshInHeader()?this.renderAppRefresh():void 0}
2137
+ .onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
2138
+ .onToggleProjects=${()=>{this.navigationSections.toggle("projects")}}
2139
+ .onToggleWorkspaces=${()=>{this.navigationSections.toggle("workspaces")}}
2140
+ .onToggleSessions=${()=>{this.navigationSections.toggle("sessions")}}
2141
+ .onSelectProject=${e=>this.selectNavigationItem("projects","workspaces",()=>this.workspaces.selectProject(e))}
2142
+ .onCloseProject=${e=>this.projects.closeProject(e.id)}
2143
+ .onSelectWorkspace=${e=>this.selectNavigationItem("workspaces","sessions",()=>this.workspaces.selectWorkspace(e))}
2144
+ .onDeleteWorkspace=${e=>{this.deleteWorkspace(e)}}
2145
+ .onArchivedCollapsed=${()=>{this.sessions.clearSelectionAfterArchivedCollapse()}}
2146
+ .onStartSession=${()=>this.selectNavigationItem("sessions","chat",()=>this.sessions.startSession())}
2147
+ .onSelectSession=${e=>this.selectNavigationItem("sessions","chat",()=>this.sessions.selectSession(e))}
2148
+ .onArchiveSession=${e=>this.sessions.archiveSession(e)}
2149
+ .onArchiveSessionWithDescendants=${e=>this.sessions.archiveSessionWithDescendants(e)}
2150
+ .onArchiveSessions=${e=>this.sessions.archiveSessions(e)}
2151
+ .onRestoreSession=${e=>this.selectNavigationItem("sessions","chat",()=>this.sessions.restoreSession(e))}
2152
+ .onDeleteCachedNewSession=${e=>this.sessions.deleteCachedNewSession(e)}
2153
+ .onDeleteArchivedSession=${e=>this.sessions.deleteArchivedSessions([e])}
2154
+ .onDeleteArchivedSessions=${e=>this.sessions.deleteArchivedSessions(e)}
2155
+ .onDetachParentSession=${e=>this.sessions.detachParent(e)}
2156
+ .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
2157
+ .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
2158
+ ></app-navigation-panel>
2159
+ `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()}),await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!ki(this.state.machines)){await this.focusNavigationSection("projects");return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView("navigation"),this.navigationSections.expand(e),await this.updateComplete,await cs(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await cs(),this.promptEditor?.focusInput()}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;if(e===void 0)return[];const t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(i=>i.visible?.(t)??!0)}workspacePanelEmptyState(){const e=this.state.selectedProject;return this.state.isLoadingProjects?{title:"Loading projects…",body:"Looking for projects you have added to PI WEB."}:e===void 0?this.state.projects.length===0?{title:"No projects yet",body:"Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace."}:{title:"Select a project",body:"Choose a project from the sidebar, then select a workspace to inspect files, Git, or terminals."}:this.state.isLoadingWorkspaces?{title:"Loading workspaces…",body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:"No workspaces found",body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:"Select a workspace",body:`Choose a workspace in ${e.name} to inspect files, Git, or terminals.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"Loading projects…":this.state.selectedWorkspace!==void 0?"Select or start a session.":this.state.selectedProject!==void 0?"Select a workspace to start a session.":this.state.projects.length===0?"Add a project to start a session.":"Select a project and workspace to start a session."}mobilePanelBadge(e){const t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case"core:workspace.files":return"files";case"core:workspace.git":return"git";case"core:workspace.terminal":return"terminal";default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){const t=qr(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>us.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=qr(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return hu({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>r.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:r},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},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 Xu(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"Reset Navigation Panel Size",description:"Restore the navigation panel to its default width",group:"View",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"Reset Workspace Panel Size",description:"Restore the workspace panel to its default width",group:"View",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"Reset Panel Sizes",description:"Restore all side panels to their default widths",group:"View",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"Focus Machines",description:"Move keyboard focus to the machine selector",shortcut:"mod+g m",group:"Navigation",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"Focus Projects",description:"Move keyboard focus to the projects list",shortcut:"mod+g p",group:"Navigation",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"Focus Workspaces",description:"Move keyboard focus to the workspaces list",shortcut:"mod+g w",group:"Navigation",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"Focus Sessions",description:"Move keyboard focus to the sessions list",shortcut:"mod+g s",group:"Navigation",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>ar())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>ar(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(o){console.warn(`Failed to register PI WEB plugin ${s.id}`,o)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>pu({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Lp(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(On(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2160
+
2161
+ This will run git worktree remove and delete:
2162
+ ${e.path}
2163
+
2164
+ The Git branch will not be deleted.`))return;const s=g(this.state);try{const o=await us.deleteWorkspace(e.projectId,e.id,s);if(g(this.state)!==s)return;this.recordWorkspaceDeletionRun(o,s);const r=await this.workspaceForCommandRun(o);if(g(this.state)!==s)return;r!==void 0&&this.openRuntimeTerminal(s,r,{terminalId:o.terminalId})}catch(o){g(this.state)===s&&this.setState({error:`Failed to start workspace deletion: ${mb(o)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(g(this.state)!==t)return;const i=Ss(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=g(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(xh(t.id));if(g(this.state)!==e)return;const s=kh(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))fi(o)||await this.handleCompletedWorkspaceDeletionRun(o,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(fi);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=g(this.state)){if(g(this.state)!==t)return;const i=Gr(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Ss(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),g(this.state)!==t)return;this.setState({workspaceDeletionRuns:vb(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"Workspace deletion failed. See terminal output."}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:""})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`Remove ${e.name}?
2165
+
2166
+ This only removes it from this PI WEB gateway.`))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:`Action failed: ${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:"Select Model",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ current":""}`,description:o}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?Hr:ns;this.setState({themeDialog:{title:"Select Theme",selectedValue:i===void 0?s:`${Qt}${i}`,options:[{value:s,label:`Auto ${this.themePreference.auto?"✓ on":"off"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${Qt}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===ns||e===Hr){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===ns},this.applyPreferredTheme(!0);return}if(!e.startsWith(Qt))return;const t=e.slice(Qt.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,hh(t),e&&ph(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return uh({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return _n(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?"Follow the system light/dark preference when the selected theme has a pair.":e.selectedThemePair===void 0?"On, but the selected theme has no light/dark pair, so it will stay selected.":`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?"light":"dark"} preference.`}themeOptionLabel(e,t){const i=[...e.id===t?["selected"]:[],...e.id===this.activeThemeId&&e.id!==t?["active"]:[]];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("auto pair"),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:"Select Thinking Level",selectedValue:t,options:e.map(i=>({value:i,label:`${i}${i===t?" ✓ current":""}`,description:wb(i)}))}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),bb(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`
2167
+ <app-context-bar
2168
+ .machines=${this.state.machines}
2169
+ .machine=${this.state.selectedMachine}
2170
+ .project=${this.state.selectedProject}
2171
+ .workspace=${this.state.selectedWorkspace}
2172
+ .session=${this.state.selectedSession}
2173
+ .refreshControl=${this.appShell.shouldShowAppRefreshInContextBar()?this.renderAppRefresh():void 0}
2174
+ .onOpenSection=${e=>{this.openNavigationSection(e)}}
2175
+ .onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
2176
+ ></app-context-bar>
2177
+ `:null}renderMobileMainTabs(){return l`
2178
+ <app-mobile-main-tabs
2179
+ .tabs=${this.mobileMainTabs()}
2180
+ .selectedView=${this.state.mainView}
2181
+ .onSelect=${e=>{this.selectMainView(e)}}
2182
+ ></app-mobile-main-tabs>
2183
+ `}mobileMainTabs(){return[{id:"navigation",label:"Sessions",icon:"navigation",className:"navigation-tab"},{id:"chat",label:"Chat",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 .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){const e=this.state;return l`
2184
+ <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
2185
+ <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
2186
+ ${this.renderNavigationPanelEdgeControl()}
2187
+ <main class=${Bn(e.mainView)}>
2188
+ ${this.renderContextBar()}
2189
+ ${this.renderMobileMainTabs()}
2190
+ ${e.error?l`<div class="error">${e.error}</div>`:null}
2191
+ <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
2192
+ ${e.selectedSession?l`
2193
+ <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>
2194
+ <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${g(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>
2195
+ <status-bar .status=${e.status}></status-bar>
2196
+ ${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}
2197
+ ${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}
2198
+ ${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}
2199
+ ${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}
2200
+ `:l`<div class="empty">${this.sessionEmptyMessage()}</div>`}
2201
+ </main>
2202
+ ${this.renderWorkspacePanelEdgeControl()}
2203
+ ${this.renderWorkspacePanel()}
2204
+ ${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}
2205
+ ${e.projectDialogOpen?l`<project-dialog .machineId=${g(e)} .onSubmit=${(t,i)=>this.projects.addProject(t,i)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
2206
+ ${e.machineDialogOpen?l`<machine-dialog .error=${e.error} .onSubmit=${t=>this.submitMachineDialog(t)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
2207
+ ${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}
2208
+ ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
2209
+ </div>
2210
+ `}};ce.styles=ff;Ie([b()],ce.prototype,"state",2);Ie([z("chat-view")],ce.prototype,"chatView",2);Ie([z("prompt-editor")],ce.prototype,"promptEditor",2);Ie([z("app-navigation-panel")],ce.prototype,"navigationPanel",2);Ie([z("#navigation-panel")],ce.prototype,"navigationPanelFrame",2);Ie([z("#workspace-panel")],ce.prototype,"workspacePanelFrame",2);Ie([b()],ce.prototype,"activeThemeId",2);Ie([b()],ce.prototype,"isRefreshingApp",2);Ie([b()],ce.prototype,"settingsSection",2);Ie([b()],ce.prototype,"shortcutConfig",2);ce=Ie([E("pi-web-app")],ce);function db(){const e=new cu;return e.register({id:"core",plugin:Kh}),e.register({id:"themes",plugin:Zh}),e}function qr(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 pb(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function hb(e,t){return Sa(e,t)}function Sa(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function ub(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function Kr(e){return Ci(e.status,e.activity)}function fb(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function Vr(){return{}}function Gr(e,t){return JSON.stringify([e,t])}function gb(e){const t=Math.min(e,Ms.length-1);return Ms[t]??3e4}function mb(e){return e instanceof Error?e.message:String(e)}function vb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function cs(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function bb(e){return e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"}function wb(e){switch(e){case"off":return"No reasoning";case"minimal":return"Very brief reasoning (~1k tokens)";case"low":return"Light reasoning (~2k tokens)";case"medium":return"Moderate reasoning (~8k tokens)";case"high":return"Deep reasoning (~16k tokens)";case"xhigh":return"Maximum reasoning (~32k tokens)"}}export{W as a,l as b,nt as c,Ab as d,z as e,Mb as f,C as i,d as n,b as r,Tb as s,E as t};