@hyperdreamer/pi-webui 1.10.6 → 1.10.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-BJJZQ999.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-BIb2Wx8W.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js"])))=>i.map(i=>d[i]);
2
2
  import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j as u,l as d,p as f,q as p,u as m}from"./vendor-editor-core-vUi74DnD.js";import{a as ee,o as te,s as ne}from"./vendor-editor-languages-DoaXUodB.js";import{n as re,t as ie}from"./vendor-terminal-D8k4UKM2.js";var ae=Object.defineProperty,oe=(e,t)=>{let n={};for(var r in e)ae(n,r,{get:e[r],enumerable:!0});return t||ae(n,Symbol.toStringTag,{value:`Module`}),n};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var se=globalThis,ce=se.ShadowRoot&&(se.ShadyCSS===void 0||se.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,le=Symbol(),ue=new WeakMap,de=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==le)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(ce&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=ue.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&ue.set(t,e))}return e}toString(){return this.cssText}},fe=e=>new de(typeof e==`string`?e:e+``,void 0,le),h=(e,...t)=>new de(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,le),pe=(e,t)=>{if(ce)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=se.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},me=ce?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return fe(t)})(e):e,{is:he,defineProperty:ge,getOwnPropertyDescriptor:_e,getOwnPropertyNames:ve,getOwnPropertySymbols:ye,getPrototypeOf:be}=Object,xe=globalThis,Se=xe.trustedTypes,Ce=Se?Se.emptyScript:``,we=xe.reactiveElementPolyfillSupport,Te=(e,t)=>e,Ee={toAttribute(e,t){switch(t){case Boolean:e=e?Ce:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},De=(e,t)=>!he(e,t),Oe={attribute:!0,type:String,converter:Ee,reflect:!1,useDefault:!1,hasChanged:De};Symbol.metadata??=Symbol(`metadata`),xe.litPropertyMetadata??=new WeakMap;var ke=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Oe){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&ge(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=_e(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Oe}static _$Ei(){if(this.hasOwnProperty(Te(`elementProperties`)))return;let e=be(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Te(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Te(`properties`))){let e=this.properties,t=[...ve(e),...ye(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(me(e))}else e!==void 0&&t.push(me(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.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(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return pe(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?Ee:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?Ee:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??De)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};ke.elementStyles=[],ke.shadowRootOptions={mode:`open`},ke[Te(`elementProperties`)]=new Map,ke[Te(`finalized`)]=new Map,we?.({ReactiveElement:ke}),(xe.reactiveElementVersions??=[]).push(`2.1.2`);var Ae=globalThis,je=e=>e,Me=Ae.trustedTypes,Ne=Me?Me.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Pe=`$lit$`,Fe=`lit$${Math.random().toFixed(9).slice(2)}$`,Ie=`?`+Fe,Le=`<${Ie}>`,Re=document,ze=()=>Re.createComment(``),Be=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Ve=Array.isArray,He=e=>Ve(e)||typeof e?.[Symbol.iterator]==`function`,Ue=`[
3
3
  \f\r]`,We=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ge=/-->/g,Ke=/>/g,qe=RegExp(`>|${Ue}(?:([^\\s"'>=/]+)(${Ue}*=${Ue}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Je=/'/g,Ye=/"/g,Xe=/^(?:script|style|textarea|title)$/i,Ze=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=Ze(1),_=Ze(2),Qe=Symbol.for(`lit-noChange`),v=Symbol.for(`lit-nothing`),$e=new WeakMap,et=Re.createTreeWalker(Re,129);function tt(e,t){if(!Ve(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ne===void 0?t:Ne.createHTML(t)}var nt=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=We;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===We?c[1]===`!--`?o=Ge:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=qe):(Xe.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=qe):o=Ke:o===qe?c[0]===`>`?(o=i??We,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?qe:c[3]===`"`?Ye:Je):o===Ye||o===Je?o=qe:o===Ge||o===Ke?o=We:(o=qe,i=void 0);let d=o===qe&&e[t+1].startsWith(`/>`)?` `:``;a+=o===We?n+Le:l>=0?(r.push(s),n.slice(0,l)+Pe+n.slice(l)+Fe+d):n+Fe+(l===-2?t:d)}return[tt(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},rt=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=nt(t,n);if(this.el=e.createElement(l,r),et.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=et.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Pe)){let t=u[o++],n=i.getAttribute(e).split(Fe),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ct:r[1]===`?`?lt:r[1]===`@`?ut:st}),i.removeAttribute(e)}else e.startsWith(Fe)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Xe.test(i.tagName)){let e=i.textContent.split(Fe),t=e.length-1;if(t>0){i.textContent=Me?Me.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],ze()),et.nextNode(),c.push({type:2,index:++a});i.append(e[t],ze())}}}else if(i.nodeType===8)if(i.data===Ie)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Fe,e+1))!==-1;)c.push({type:7,index:a}),e+=Fe.length-1}a++}}static createElement(e,t){let n=Re.createElement(`template`);return n.innerHTML=e,n}};function it(e,t,n=e,r){if(t===Qe)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Be(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=it(e,i._$AS(e,t.values),i,r)),t}var at=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??Re).importNode(t,!0);et.currentNode=r;let i=et.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new ot(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new dt(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=et.nextNode(),a++)}return et.currentNode=Re,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},ot=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=v,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=it(this,e,t),Be(e)?e===v||e==null||e===``?(this._$AH!==v&&this._$AR(),this._$AH=v):e!==this._$AH&&e!==Qe&&this._(e):e._$litType$===void 0?e.nodeType===void 0?He(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==v&&Be(this._$AH)?this._$AA.nextSibling.data=e:this.T(Re.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=rt.createElement(tt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new at(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=$e.get(e.strings);return t===void 0&&$e.set(e.strings,t=new rt(e)),t}k(t){Ve(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(ze()),this.O(ze()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=je(e).nextSibling;je(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},st=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=v,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=v}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=it(this,e,t,0),a=!Be(e)||e!==this._$AH&&e!==Qe,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=it(this,r[n+o],t,o),s===Qe&&(s=this._$AH[o]),a||=!Be(s)||s!==this._$AH[o],s===v?e=v:e!==v&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===v?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},ct=class extends st{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===v?void 0:e}},lt=class extends st{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==v)}},ut=class extends st{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=it(this,e,t,0)??v)===Qe)return;let n=this._$AH,r=e===v&&n!==v||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==v&&(n===v||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},dt=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){it(this,e)}},ft={M:Pe,P:Fe,A:Ie,C:1,L:nt,R:at,D:He,V:it,I:ot,H:st,N:lt,U:ut,B:ct,F:dt},pt=Ae.litHtmlPolyfillSupport;pt?.(rt,ot),(Ae.litHtmlVersions??=[]).push(`3.3.3`);var mt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new ot(t.insertBefore(ze(),e),e,void 0,n??{})}return i._$AI(e),i},ht=globalThis,y=class extends ke{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=mt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Qe}};y._$litElement$=!0,y.finalized=!0,ht.litElementHydrateSupport?.({LitElement:y});var gt=ht.litElementPolyfillSupport;gt?.({LitElement:y}),(ht.litElementVersions??=[]).push(`4.2.2`);var b=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},_t={attribute:!0,type:String,converter:Ee,reflect:!1,hasChanged:De},vt=(e=_t,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function x(e){return(t,n)=>typeof n==`object`?vt(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function S(e){return x({...e,state:!0,attribute:!1})}var yt=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function C(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return yt(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return yt(n,r,{get(){return a(this)}})}}function bt(e,t=St()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(Ct(e),n).toString()}function xt(e,t=St()){let n=new URL(bt(e,t));if(n.protocol===`http:`)n.protocol=`ws:`;else if(n.protocol===`https:`)n.protocol=`wss:`;else throw Error(`Cannot create a WebSocket URL from ${n.protocol}`);return n.toString()}function St(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function Ct(e){return e.startsWith(`/`)?`.${e}`:e}async function w(e,t,n){let r=new Headers(n?.headers);n?.body!==void 0&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await fetch(bt(e),{...n,headers:r});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(wt(e)??i.statusText)}return t(await i.json())}function wt(e){if(Tt(e))return typeof e.error==`string`?e.error:void 0}function Tt(e){return typeof e==`object`&&!!e}var T={sessionsDeleteArchived:`sessions.deleteArchived`,sessionsBulkMutations:`sessions.bulkMutations`,sessionsCleanup:`sessions.cleanup`,sessionsReload:`sessions.reload`,sessionsClearQueue:`sessions.clearQueue`,sessionsMessageActions:`sessions.messageActions`,sessionsSystemPrompt:`sessions.systemPrompt`,sessionsPersistedState:`sessions.persistedState`,sessionsNotifications:`sessions.notifications`,sessionsUnread:`sessions.unread`,promptAttachments:`prompt.attachments`,workspaceFileSuggestions:`workspace.fileSuggestions`,piPackagesManage:`piPackages.manage`,selectedMachineSettings:`settings.selectedMachine`,agentProfileConfig:`settings.agentProfile`},Et=1e3,Dt=32*1024,Ot=8*1024,kt=1e4;function At(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function jt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&At(e)}var Mt=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),Nt=/^sha256:[0-9a-f]{64}$/u,Pt=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,Ft=new Set([`PI_WEBUI_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function It(e){if(!Vt(e)||Object.keys(e).some(e=>!Mt.has(e)))return;let t=e.schemaVersion,n=e.revision,r=e.command,i=e.dir,a=e.sessionDirEnvKeys;if(t===1&&!(typeof n!=`string`||!Nt.test(n))&&!(typeof r!=`string`||!Lt(r))&&!(typeof i!=`string`||!Rt(i))&&Bt(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEBUI_AGENT_SESSION_DIR`||a.some(e=>!Ft.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Lt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:Rt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):Pt.test(e)}function Rt(e){if(e===``||e!==e.trim()||zt(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function zt(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Bt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Vt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ht=Object.values(T),Ut=new Set(Ht);T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsMessageActions,T.sessionsSystemPrompt,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.promptAttachments,T.workspaceFileSuggestions,T.piPackagesManage,T.selectedMachineSettings,T.agentProfileConfig,T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsMessageActions,T.sessionsSystemPrompt,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.promptAttachments,T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsMessageActions,T.sessionsSystemPrompt,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.promptAttachments,T.workspaceFileSuggestions,T.piPackagesManage,T.selectedMachineSettings,T.agentProfileConfig;function Wt(e){return typeof e==`string`&&Ut.has(e)}function Gt(e,t){return e?.capabilities?.includes(t)===!0}function Kt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Wt)}function qt(e){return typeof e==`object`&&!!e}function E(e){if(!qt(e))throw Error(`Expected object response`);return e}function D(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function O(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function k(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function A(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function j(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function Jt(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function Yt(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Xt(e){if(!qt(e)||typeof e.kind!=`string`)throw Error(`Invalid memory snapshot response`);if(e.kind===`unavailable`)return{kind:`unavailable`};if(e.kind!==`data`)throw Error(`Invalid memory snapshot response`);return{kind:`data`,globalEntries:Zt(e.globalEntries),projectEntries:Zt(e.projectEntries),...typeof e.projectUnavailableMessage==`string`?{projectUnavailableMessage:e.projectUnavailableMessage}:{}}}function Zt(e){if(!Array.isArray(e))throw Error(`Invalid memory snapshot response`);return e.map(e=>{if(!qt(e)||typeof e.id!=`string`||typeof e.content!=`string`)throw Error(`Invalid memory snapshot response`);return{id:e.id,content:e.content,...typeof e.category==`string`?{category:e.category}:{},...typeof e.created==`string`?{created:e.created}:{},...typeof e.last==`string`?{last:e.last}:{},...typeof e.failureReason==`string`?{failureReason:e.failureReason}:{}}})}function Qt(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=E(e);return{messages:Jt(t.messages),start:k(t,`start`),total:k(t,`total`)}}function $t(e){let t=E(e);return j(en)(t.machines)}function en(e){let t=E(e),n=rn(t,`kind`),r=O(t,`baseUrl`),i=an(t,`status`),a=O(t,`statusMessage`);return{id:D(t,`id`),name:D(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:D(t,`createdAt`),updatedAt:D(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function tn(e){let t=E(e),n=an(t,`status`),r=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:Hi(t.web)},...t.sessiond===void 0?{}:{sessiond:Hi(t.sessiond)},...r===void 0?{}:{error:r}}}function nn(e){let t=E(e),n=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...N(`packageName`,O(t,`packageName`)),...N(`generatedAt`,O(t,`generatedAt`)),...t.components===void 0?{}:{components:Bi(t.components)},...t.capabilities===void 0?{}:{capabilities:Ji(t.capabilities)},...n===void 0?{}:{error:n}}}function rn(e,t){let n=D(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function an(e,t){let n=O(e,t);if(n!==void 0){if(n!==`unknown`&&n!==`online`&&n!==`offline`&&n!==`error`)throw Error(`Expected machine status field: ${t}`);return n}}function on(e){let t=E(e);return{id:D(t,`id`),name:D(t,`name`),path:D(t,`path`),createdAt:D(t,`createdAt`)}}function sn(e){let t=E(e),n=O(t,`branch`);return{id:D(t,`id`),projectId:D(t,`projectId`),path:D(t,`path`),label:D(t,`label`),...n===void 0?{}:{branch:n},isMain:A(t,`isMain`),isGitRepo:A(t,`isGitRepo`),isGitWorktree:A(t,`isGitWorktree`),...N(`effectiveConfig`,cn(t.effectiveConfig))}}function cn(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...N(`uploads`,pi(e.uploads))}}}function ln(e){let t=E(e),n=O(t,`name`),r=Ii(t.persisted,`persisted`),i=O(t,`parentSessionPath`),a=O(t,`archivedAt`),o=Ii(t.pinned,`pinned`);return{id:D(t,`id`),path:D(t,`path`),cwd:D(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:D(t,`created`),modified:D(t,`modified`),messageCount:k(t,`messageCount`),firstMessage:D(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a},...o===void 0?{}:{pinned:o}}}function un(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function dn(e){if(e!==void 0)return{id:D(E(e),`id`)}}function fn(e){let t=E(e),n=dn(t.dismiss);return{severity:un(t.severity),message:D(t,`message`),...N(`source`,O(t,`source`)),...N(`path`,O(t,`path`)),...n===void 0?{}:{dismiss:n}}}function pn(e){return e===void 0?{}:{warnings:j(fn)(e)}}function mn(e){let t=E(e);return{sessionId:D(t,`sessionId`),...N(`persisted`,Ii(t.persisted,`persisted`)),isStreaming:A(t,`isStreaming`),isCompacting:A(t,`isCompacting`),isBashRunning:A(t,`isBashRunning`),pendingMessageCount:k(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:j(Yn)(t.queuedMessages),...N(`messageCount`,M(t,`messageCount`)),tokens:Xn(t.tokens),cost:k(t,`cost`),...Br(t.generation),...Qn(t.model),...Vr(t.contextUsage),...N(`thinkingLevel`,O(t,`thinkingLevel`)),...pn(t.warnings)}}function hn(e){let t=E(e);return{seq:k(t,`seq`),partial:t.partial??null}}function gn(e){let t=O(E(e),`systemPrompt`);return t===void 0?{}:{systemPrompt:t}}function _n(e){let t=E(e),n=In(t,`catalogRevision`),r=Nn(t.sessions,yn,Et,`sessions`);if(bn(r),xn(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:Sn(t,`catalogId`,512),catalogRevision:n,sessions:r}}function vn(e){let t=E(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=Sn(t,`sessionId`,512),r=Sn(t,`cwd`,Dt),i=Cn(t,`catalogRevision`),a=t.unread===null?null:yn(t.unread);if(a!==null&&(a.sessionId!==n||a.cwd!==r))throw Error(`Session unread event identity mismatch`);if(a!==null&&a.completionOrder>i)throw Error(`Session unread completion order exceeds catalog revision`);return{type:`sessions.unread`,catalogId:Sn(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function yn(e){let t=E(e),n=Sn(t,`completedAt`,64),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical session unread completion time`);return{sessionId:Sn(t,`sessionId`,512),cwd:Sn(t,`cwd`,Dt),completionOrder:Cn(t,`completionOrder`),completedAt:n}}function bn(e){let t=e.map(e=>JSON.stringify([e.sessionId,e.cwd]));if(new Set(t).size!==t.length)throw Error(`Duplicate session unread identity`);let n=e.map(e=>e.completionOrder);if(new Set(n).size!==n.length)throw Error(`Duplicate session unread completion order`)}function xn(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.completionOrder<=r.completionOrder)throw Error(`Session unread summaries are not newest-first`)}}function Sn(e,t,n){let r=Fn(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Cn(e,t){let n=In(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function wn(e){let t=E(e),n=En(t.summary),r=Nn(t.notifications,Dn,100,`notifications`);if(Ln(r),Rn(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==Bn(r))throw Error(`Notification snapshot severity mismatch`);let i=On(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:Fn(t,`daemonInstanceId`),catalogRevision:In(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Tn(e){let t=E(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=En(t.summary),r=On(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=kn(t.delta);if(i.kind===`cleared`&&!zn(n))throw Error(`Notification clear event summary mismatch`);if(i.kind===`added`&&n.retainedCount===0)throw Error(`Notification add event summary mismatch`);return{type:`notifications.inbox`,daemonInstanceId:Fn(t,`daemonInstanceId`),catalogRevision:In(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function En(e){let t=E(e),n=In(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=In(t,`discardedCount`),i=jn(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:Fn(t,`sessionId`),cwd:Fn(t,`cwd`),inboxRevision:In(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Dn(e){let t=E(e),n=D(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=D(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=In(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:Fn(t,`id`),message:n,truncated:A(t,`truncated`),severity:An(t.severity),receivedAt:r,order:i}}function On(e){let t=E(e);return{order:In(t,`order`),overflowWatermark:In(t,`overflowWatermark`)}}function kn(e){let t=E(e);switch(t.kind){case`added`:{let e=O(t,`evictedNotificationId`);return{kind:`added`,notification:Dn(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=Nn(t.notificationIds,Pn,100,`notificationIds`);if(new Set(e).size!==e.length)throw Error(`Duplicate dismissed notification id`);return{kind:`dismissed`,notificationIds:e}}case`cleared`:return{kind:`cleared`,reason:Mn(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function An(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function jn(e){return e===void 0?void 0:An(e)}function Mn(e){switch(e){case`runtime-close`:case`archive`:case`delete`:case`restore`:case`archive-reconcile`:case`replacement`:case`initialization-failed`:case`service-dispose`:return e;default:throw Error(`Invalid notification clear reason`)}}function Nn(e,t,n,r){if(!Array.isArray(e))throw Error(`Expected array field: ${r}`);if(e.length>n)throw Error(`Array field exceeds limit: ${r}`);return e.map(t)}function Pn(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function Fn(e,t){let n=D(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function In(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Expected non-negative safe integer field: ${t}`);return n}function Ln(e){if(new Set(e.map(e=>e.id)).size!==e.length)throw Error(`Duplicate notification id`);if(new Set(e.map(e=>e.order)).size!==e.length)throw Error(`Duplicate notification order`)}function Rn(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.order<=r.order)throw Error(`Notifications are not newest-first`)}}function zn(e){return e.retainedCount===0&&e.discardedCount===0}function Bn(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Vn(e){let t=E(e),n=t.skippedBusySessionIds===void 0?void 0:Yt(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:D(t,`generatedAt`),thresholds:Kn(t.thresholds),projects:j(qn)(t.projects),totals:Jn(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Hn(e){let t=E(e);return{...Vn(t),archivedSessionIds:Yt(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:Yt(t.deletedSessionIds,`deletedSessionIds`)}}function Un(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:Yt(t.archivedSessionIds,`archivedSessionIds`),failures:j(Gn)(t.failures),generatedAt:D(t,`generatedAt`)}}function Wn(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:Yt(t.deletedSessionIds,`deletedSessionIds`),failures:j(Gn)(t.failures),generatedAt:D(t,`generatedAt`)}}function Gn(e){let t=E(e);return{sessionId:D(t,`sessionId`),error:D(t,`error`)}}function Kn(e){let t=E(e);return{...N(`archiveIdleDays`,M(t,`archiveIdleDays`)),...N(`deleteArchivedDays`,M(t,`deleteArchivedDays`))}}function qn(e){let t=E(e);return{cwd:D(t,`cwd`),archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function Jn(e){let t=E(e);return{archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function Yn(e){let t=E(e),n=D(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:D(t,`text`)}}function Xn(e){let t=E(e);return{input:k(t,`input`),output:k(t,`output`),cacheRead:k(t,`cacheRead`),cacheWrite:k(t,`cacheWrite`),total:k(t,`total`)}}function Zn(e){let t=E(e);return{...N(`provider`,O(t,`provider`)),...N(`id`,O(t,`id`)),...N(`name`,O(t,`name`)),...N(`contextWindow`,M(t,`contextWindow`)),...N(`reasoning`,t.reasoning)}}function Qn(e){return e===void 0?{}:{model:Zn(e)}}function $n(e){let t=E(e);return{models:j(Zn)(t.models)}}function er(e){let t=E(e);return{...t.model===void 0?{}:{model:Zn(t.model)},thinkingLevel:D(t,`thinkingLevel`),models:j(Zn)(t.models),thinkingLevels:Yt(t.thinkingLevels,`thinkingLevels`)}}function tr(e){let t=ir(e,`models configuration`),n=t.providers;if(n===void 0)return{...t,providers:{}};let r=ir(n,`models configuration providers`),i={};for(let[e,t]of Object.entries(r))i[e]=nr(t);return{...t,providers:i}}function nr(e){let t=ir(e,`models configuration provider`),n={};for(let[e,r]of Object.entries(t))n[e]=r;let r=O(t,`baseUrl`);r!==void 0&&(n.baseUrl=r);let i=O(t,`api`);i!==void 0&&(n.api=i);let a=O(t,`apiKey`);a!==void 0&&(n.apiKey=a);let o=ar(t.headers,`models configuration provider headers`);o!==void 0&&(n.headers=or(o,`models configuration provider headers`));let s=ar(t.compat,`models configuration provider compatibility`);s!==void 0&&(n.compat={...s});let c=ar(t.modelOverrides,`models configuration provider model overrides`);c!==void 0&&(n.modelOverrides={...c});let l=t.models;if(l!==void 0){if(!Array.isArray(l))throw Error(`Expected models configuration models array`);n.models=l.map(rr)}return n}function rr(e){let t=ir(e,`models configuration model`),n={id:D(t,`id`)};for(let[e,r]of Object.entries(t))n[e]=r;n.id=D(t,`id`);let r=O(t,`name`);r!==void 0&&(n.name=r);let i=O(t,`api`);i!==void 0&&(n.api=i);let a=ya(t,`reasoning`);a!==void 0&&(n.reasoning=a);let o=ar(t.thinkingLevelMap,`models configuration thinking level map`);o!==void 0&&(n.thinkingLevelMap=sr(o));let s=t.input;if(s!==void 0){if(!Array.isArray(s)||!s.every(e=>typeof e==`string`))throw Error(`Expected models configuration model input array of strings`);n.input=[...s]}let c=M(t,`contextWindow`);c!==void 0&&(n.contextWindow=c);let l=M(t,`maxTokens`);l!==void 0&&(n.maxTokens=l);let u=ar(t.cost,`models configuration model cost`);u!==void 0&&(n.cost=cr(u));let d=ar(t.compat,`models configuration model compatibility`);return d!==void 0&&(n.compat={...d}),n}function ir(e,t){if(!qt(e)||Array.isArray(e))throw Error(`Expected ${t} object`);return e}function ar(e,t){if(e!==void 0)return ir(e,t)}function or(e,t){let n={};for(let[r,i]of Object.entries(e)){if(typeof i!=`string`)throw Error(`Expected ${t} values to be strings`);n[r]=i}return n}function sr(e){let t={};for(let[n,r]of Object.entries(e)){if(r!==null&&typeof r!=`string`)throw Error(`Expected models configuration thinking level map values to be strings or null`);t[n]=r}return t}function cr(e){let t={};for(let n of[`input`,`output`,`cacheRead`,`cacheWrite`]){let r=e[n];if(r!==void 0){if(typeof r!=`number`)throw Error(`Expected models configuration model cost ${n} to be a number`);t[n]=r}}return t}function lr(e){if(E(e).success!==!0)throw Error(`Expected successful models configuration save`);return{success:!0}}function ur(e){let t=E(e);return{models:j(dr)(t.models)}}function dr(e){let t=E(e),n=D(t,`id`),r=O(t,`name`);return r===void 0?{id:n}:{id:n,name:r}}function fr(e){let t=E(e),n=A(t,`ok`),r=O(t,`error`),i=t.latencyMs===void 0?void 0:k(t,`latencyMs`),a=t.status===void 0?void 0:k(t,`status`),o=O(t,`responseText`);return{ok:n,...r===void 0?{}:{error:r},...i===void 0?{}:{latencyMs:i},...a===void 0?{}:{status:a},...o===void 0?{}:{responseText:o}}}function pr(e){let t=E(e);return{skills:j(mr)(t.skills)}}function mr(e){let t=E(e),n=E(t.sourceInfo),r=O(n,`source`),i=O(n,`scope`);return{name:D(t,`name`),description:D(t,`description`),filePath:D(t,`filePath`),baseDir:D(t,`baseDir`),disableModelInvocation:A(t,`disableModelInvocation`),sourceInfo:{...r===void 0?{}:{source:r},...i===void 0?{}:{scope:i}},...t.install===void 0?{}:{install:hr(t.install)}}}function hr(e){let t=E(e),n=O(t,`sourceType`),r=O(t,`skillsShUrl`),i=O(t,`skillPath`),a=O(t,`ref`),o=O(t,`versionHash`);return{package:D(t,`package`),scope:gr(t.scope),source:D(t,`source`),...n===void 0?{}:{sourceType:n},...r===void 0?{}:{skillsShUrl:r},...i===void 0?{}:{skillPath:i},...a===void 0?{}:{ref:a},...o===void 0?{}:{versionHash:o},canCheckForUpdates:A(t,`canCheckForUpdates`)}}function gr(e){if(e!==`global`&&e!==`project`)throw Error(`Expected skill install scope`);return e}function _r(e){if(E(e).success!==!0)throw Error(`Expected successful Skills mutation`);return{success:!0}}function vr(e){let t=E(e);return{results:j(yr)(t.results)}}function yr(e){let t=E(e);return{package:D(t,`package`),installs:D(t,`installs`),url:D(t,`url`)}}function br(e){let t=E(e);return{updates:j(xr)(t.updates)}}function xr(e){let t=E(e),n=O(t,`currentVersion`),r=O(t,`latestVersion`),i=O(t,`message`);return{package:D(t,`package`),scope:gr(t.scope),state:Sr(t.state),...n===void 0?{}:{currentVersion:n},...r===void 0?{}:{latestVersion:r},...i===void 0?{}:{message:i}}}function Sr(e){if(e!==`up-to-date`&&e!==`update-available`&&e!==`unsupported`&&e!==`error`)throw Error(`Expected skill update state`);return e}function Cr(e){let t=E(e);if(t.success!==!0)throw Error(`Expected successful Skills update`);let n=O(t,`output`);return{success:!0,...t.skill===void 0?{}:{skill:mr(t.skill)},...n===void 0?{}:{output:n}}}function wr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Tr(e){let t=E(e);return{levels:j(wr)(t.levels)}}function Er(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Dr(e){if(e!==`stored`&&e!==`runtime`&&e!==`environment`&&e!==`fallback`&&e!==`models_json_key`&&e!==`models_json_command`)throw Error(`Invalid auth status source`);return e}function Or(e){let t=E(e),n=t.source===void 0?void 0:Dr(t.source);return{configured:A(t,`configured`),...N(`source`,n),...N(`label`,O(t,`label`))}}function kr(e){let t=E(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:D(t,`id`),name:D(t,`name`),authType:Er(t.authType),status:Or(t.status),...n===void 0?{}:{loginFlow:n}}}function Ar(e){let t=E(e);return{providers:j(kr)(t.providers)}}function jr(e){let t=E(e);return{flowId:D(t,`flowId`),providerId:D(t,`providerId`),providerName:D(t,`providerName`),status:Mr(t.status),progress:j(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...N(`error`,O(t,`error`)),...N(`auth`,Nr(t.auth)),...N(`prompt`,Fr(t.prompt)),...N(`select`,Lr(t.select)),...N(`info`,Rr(t.info))}}function Mr(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function Nr(e){if(e===void 0)return;let t=E(e);return{url:D(t,`url`),...N(`instructions`,O(t,`instructions`)),...N(`deviceCode`,Pr(t.deviceCode))}}function Pr(e){if(e===void 0)return;let t=E(e);return{userCode:D(t,`userCode`),...N(`intervalSeconds`,M(t,`intervalSeconds`)),...N(`expiresInSeconds`,M(t,`expiresInSeconds`))}}function Fr(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0?n===`manual`?`manual_code`:`text`:Ir(t.promptType);return{requestId:D(t,`requestId`),message:D(t,`message`),kind:n,promptType:r,...N(`placeholder`,O(t,`placeholder`)),...N(`allowEmpty`,ya(t,`allowEmpty`))}}function Ir(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function Lr(e){if(e===void 0)return;let t=E(e);return{requestId:D(t,`requestId`),message:D(t,`message`),options:j(oa)(t.options)}}function Rr(e){if(e!==void 0)return j(e=>{let t=E(e);return{message:D(t,`message`),...N(`links`,t.links===void 0?void 0:j(zr)(t.links))}})(e)}function zr(e){let t=E(e);return{url:D(t,`url`),...N(`label`,O(t,`label`))}}function Br(e){if(e===void 0)return{};let t=E(e);return{generation:{outputTokens:k(t,`outputTokens`),...N(`tokensPerSecond`,M(t,`tokensPerSecond`)),...N(`estimated`,ya(t,`estimated`))}}}function Vr(e){if(e===void 0)return{};let t=E(e);return{contextUsage:{tokens:ba(t,`tokens`),contextWindow:k(t,`contextWindow`),percent:ba(t,`percent`)}}}function Hr(e){let t=E(e),n=D(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:D(t,`name`),source:n,...N(`description`,O(t,`description`))}}function Ur(e){let t=E(e),n=D(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:D(t,`path`),kind:n}}function Wr(e){let t=E(e);return{path:D(t,`path`),entries:j(Gr)(t.entries),scannedAt:D(t,`scannedAt`),truncated:A(t,`truncated`)}}function Gr(e){let t=E(e),n=D(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:D(t,`name`),path:D(t,`path`),type:n,...N(`size`,M(t,`size`)),...N(`modifiedAt`,O(t,`modifiedAt`))}}function Kr(e){let t=E(e),n=D(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:D(t,`path`),...N(`language`,O(t,`language`)),...N(`mediaType`,Xr(t.mediaType)),...N(`mimeType`,O(t,`mimeType`)),encoding:n,size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),content:D(t,`content`),truncated:A(t,`truncated`),binary:A(t,`binary`)}}function qr(e){let t=E(e);return{path:D(t,`path`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),created:A(t,`created`)}}function Jr(e){let t=E(e);return{path:D(t,`path`),existed:A(t,`existed`)}}function Yr(e){let t=E(e);return{fromPath:D(t,`fromPath`),toPath:D(t,`toPath`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`)}}function Xr(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function Zr(e){let t=E(e);return{isGitRepo:A(t,`isGitRepo`),hash:D(t,`hash`),...N(`branch`,O(t,`branch`)),...N(`latestTag`,O(t,`latestTag`)),...N(`upstream`,O(t,`upstream`)),...N(`ahead`,M(t,`ahead`)),...N(`behind`,M(t,`behind`)),files:j(Qr)(t.files)}}function Qr(e){let t=E(e);return{path:D(t,`path`),...N(`oldPath`,O(t,`oldPath`)),index:$r(t.index),workingTree:$r(t.workingTree)}}function $r(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 Error(`Invalid git file state`)}}function ei(e){let t=E(e);return{...N(`path`,O(t,`path`)),staged:A(t,`staged`),hash:D(t,`hash`),diff:D(t,`diff`),truncated:A(t,`truncated`)}}function ti(e){let t=E(e);return{id:D(t,`id`),cwd:D(t,`cwd`),name:D(t,`name`),createdAt:D(t,`createdAt`),exited:A(t,`exited`),...N(`exitCode`,M(t,`exitCode`)),...N(`commandRunId`,O(t,`commandRunId`))}}function ni(e){let t=E(e);return{id:D(t,`id`),origin:D(t,`origin`),projectId:D(t,`projectId`),workspaceId:D(t,`workspaceId`),terminalId:D(t,`terminalId`),title:D(t,`title`),command:D(t,`command`),status:ri(t.status),...N(`exitCode`,M(t,`exitCode`)),createdAt:D(t,`createdAt`),...N(`startedAt`,O(t,`startedAt`)),...N(`completedAt`,O(t,`completedAt`)),metadata:ii(t.metadata,`metadata`)}}function ri(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function ii(e,t){let n=E(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function ai(e){let t=E(e);return{cwd:D(t,`cwd`),hasSessionActivity:A(t,`hasSessionActivity`),hasTerminalActivity:A(t,`hasTerminalActivity`),updatedAt:D(t,`updatedAt`)}}function oi(e){let t=E(e);return{workspaces:j(ai)(t.workspaces),generatedAt:D(t,`generatedAt`)}}function si(e){let t=E(e);return{path:D(t,`path`),exists:A(t,`exists`),config:ci(t.config),effectiveConfig:ci(t.effectiveConfig),envOverrides:vi(t.envOverrides)}}function ci(e){let t=E(e);return{...N(`host`,O(t,`host`)),...N(`port`,M(t,`port`)),...N(`allowedHosts`,ui(t.allowedHosts)),...N(`shortcuts`,gi(t.shortcuts)),...N(`plugins`,_i(t.plugins)),...N(`pathAccess`,di(t.pathAccess)),...N(`uploads`,pi(t.uploads)),...N(`maxUploadBytes`,M(t,`maxUploadBytes`)),...N(`agent`,li(t.agent)),...N(`spawnSessions`,ya(t,`spawnSessions`)),...N(`subsessions`,ya(t,`subsessions`))}}function li(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI agent field`);return{...N(`command`,O(e,`command`)),...N(`dir`,O(e,`dir`))}}}function ui(e){if(e!==void 0){if(e===!0)return!0;if(mi(e))return e;throw Error(`Invalid PI WEBUI allowedHosts field`)}}function di(e){if(e===void 0)return;if(!qt(e))throw Error(`Invalid PI WEBUI pathAccess field`);let t=e.allowedPaths;return{...N(`allowedPaths`,fi(t,`pathAccess.allowedPaths`))}}function fi(e,t){if(e!==void 0){if(hi(e))return e;throw Error(`Invalid PI WEBUI ${t} field`)}}function pi(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI uploads field`);return{...N(`defaultFolder`,O(e,`defaultFolder`))}}}function mi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function hi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function gi(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEBUI shortcut field`);return[e,t]}))}}function _i(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!qt(t)||Array.isArray(t))throw Error(`Invalid PI WEBUI plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEBUI plugin enabled field`);let r=t.settings;if(r!==void 0&&(!qt(r)||Array.isArray(r)))throw Error(`Invalid PI WEBUI plugin settings field`);return[e,t]}))}}function vi(e){let t=E(e);return{host:A(t,`host`),port:A(t,`port`),allowedHosts:A(t,`allowedHosts`),spawnSessions:A(t,`spawnSessions`),subsessions:A(t,`subsessions`),agentCommand:ya(t,`agentCommand`)??!1,agentDir:ya(t,`agentDir`)??!1,...yi(t),agentSessionDir:ya(t,`agentSessionDir`)??!1}}function yi(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-webui`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEBUI agentDirSource field`);return{agentDirSource:t}}function bi(e){let t=E(e);return{packages:j(Si)(t.packages)}}function xi(e){let t=E(e),n=O(t,`source`),r=t.scope===void 0?void 0:Ci(t.scope),i=Ii(t.removed,`removed`);return{action:wi(t.action),...N(`source`,n),...N(`scope`,r),...N(`removed`,i),packages:j(Si)(t.packages)}}function Si(e){let t=E(e);return{source:D(t,`source`),scope:Ci(t.scope),filtered:A(t,`filtered`),...N(`installedPath`,O(t,`installedPath`))}}function Ci(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function wi(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Ti(e){let t=E(e);return{packages:j(Ei)(t.packages),totals:ki(t.totals),diagnostics:j(Mi)(t.diagnostics)}}function Ei(e){let t=E(e);return{source:D(t,`source`),scope:Di(t.scope),filtered:A(t,`filtered`),disabled:A(t,`disabled`),...N(`installedPath`,O(t,`installedPath`)),...N(`packageName`,O(t,`packageName`)),...N(`version`,O(t,`version`)),...N(`configuredVersion`,O(t,`configuredVersion`)),counts:ki(t.counts),resources:j(Ai)(t.resources),status:Oi(t.status)}}function Di(e){if(e!==`global`&&e!==`project`)throw Error(`Invalid Pi package plugin scope`);return e}function Oi(e){if(e!==`loaded`&&e!==`installed`&&e!==`missing`&&e!==`disabled`)throw Error(`Invalid Pi package plugin status`);return e}function ki(e){let t=E(e);return{extensions:k(t,`extensions`),skills:k(t,`skills`),prompts:k(t,`prompts`),themes:k(t,`themes`)}}function Ai(e){let t=E(e);return{kind:ji(t.kind),name:D(t,`name`),path:D(t,`path`),relativePath:D(t,`relativePath`)}}function ji(e){if(e!==`extension`&&e!==`skill`&&e!==`prompt`&&e!==`theme`)throw Error(`Invalid Pi package plugin resource kind`);return e}function Mi(e){let t=E(e),n=t.type;if(n!==`warning`&&n!==`error`)throw Error(`Invalid Pi package plugin diagnostic type`);return{type:n,message:D(t,`message`),...N(`source`,O(t,`source`)),...N(`path`,O(t,`path`))}}function Ni(e){let t=E(e);return{plugins:j(Pi)(t.plugins)}}function Pi(e){let t=E(e);return{id:D(t,`id`),module:D(t,`module`),source:D(t,`source`),scope:Fi(t.scope),machineSpecific:Ii(t.machineSpecific,`machineSpecific`)??!1,enabled:A(t,`enabled`)}}function Fi(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEBUI plugin scope`);return e}function Ii(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function Li(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:zi(t.components),release:Wi(t.release),commands:Gi(t.commands),messages:j(Ki)(t.messages)}}function Ri(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Bi(t.components),capabilities:Ji(t.capabilities)}}function zi(e){let t=E(e);return{web:Hi(t.web),sessiond:Hi(t.sessiond)}}function Bi(e){let t=E(e);return{web:Vi(t.web),sessiond:Vi(t.sessiond)}}function Vi(e){let t=E(e),n=qi(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:It(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:D(t,`label`),...N(`runtimeVersion`,O(t,`runtimeVersion`)),available:A(t,`available`),capabilities:Ji(t.capabilities),...N(`activeAgentProfile`,i),...N(`error`,O(t,`error`))}}function Hi(e){let t=E(e);return{component:qi(t.component),label:D(t,`label`),...N(`runtimeVersion`,O(t,`runtimeVersion`)),...N(`installedVersion`,O(t,`installedVersion`)),stale:A(t,`stale`),available:A(t,`available`),...N(`installation`,Ui(t.installation)),...N(`error`,O(t,`error`))}}function Ui(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEBUI installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEBUI installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEBUI Docker mode`);return{kind:n,...N(`path`,O(t,`path`)),...N(`source`,O(t,`source`)),...r===void 0?{}:{scope:r},...N(`npmRoot`,O(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function Wi(e){let t=E(e);return{packageName:D(t,`packageName`),...N(`latestVersion`,O(t,`latestVersion`)),updateAvailable:A(t,`updateAvailable`),...N(`checkedAt`,O(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...N(`error`,O(t,`error`))}}function Gi(e){let t=E(e);return{...N(`update`,O(t,`update`)),...N(`restart`,O(t,`restart`)),...N(`restartWeb`,O(t,`restartWeb`)),...N(`restartSessiond`,O(t,`restartSessiond`)),...N(`status`,O(t,`status`))}}function Ki(e){let t=E(e);return{id:D(t,`id`),severity:Yi(t.severity),title:D(t,`title`),body:D(t,`body`),...N(`command`,O(t,`command`))}}function qi(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEBUI service component`);return e}function Ji(e){let t=Kt(e);if(t===void 0)throw Error(`Invalid PI WEBUI capabilities`);return t}function Yi(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEBUI status severity`);return e}function Xi(e){let t=E(e),n=D(t,`type`);if(n===`unsupported`)return{type:n,message:D(t,`message`)};if(n===`select`)return{type:n,requestId:D(t,`requestId`),title:D(t,`title`),options:j(oa)(t.options)};if(n===`tree`)return{type:n,tree:Zi(t.tree)};if(n===`done`)return{type:n,...N(`message`,O(t,`message`)),...sa(t.session),...N(`promptDraft`,O(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Zi(e){let t=E(e),n=j(Qi)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=ra(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:aa(t.activePathIds,`activePathIds`)}}function Qi(e){let t=E(e);return{id:ia(t,`id`),parentId:ra(t,`parentId`),kind:$i(t.kind),summary:D(t,`summary`),...N(`timestamp`,O(t,`timestamp`)),...N(`label`,O(t,`label`))}}function $i(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`compaction`:case`branch-summary`:case`model-change`:case`thinking-level-change`:case`session-info`:case`label`:case`custom`:case`other`:return e;default:throw Error(`Invalid session tree node kind`)}}function ea(e){let t=E(e),n=A(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){na(t,`editorText`,`session tree cancellation result`);let e=t.aborted;if(e!==void 0&&typeof e!=`boolean`)throw Error(`Expected optional boolean field: aborted`);return{cancelled:n,...e===void 0?{}:{aborted:e}}}return na(t,`aborted`,`session tree navigation result`),{cancelled:n,...N(`editorText`,O(t,`editorText`))}}function ta(e){let t=E(e);return A(t,`cancelled`)?(na(t,`session`,`session fork cancellation result`),{cancelled:!0}):{cancelled:!1,session:ln(t.session)}}function na(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function ra(e,t){let n=e[t];if(n!==null&&typeof n!=`string`)throw Error(`Expected string or null field: ${t}`);if(typeof n==`string`&&n.trim()===``)throw Error(`Expected non-blank string or null field: ${t}`);return n}function ia(e,t){let n=D(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function aa(e,t){let n=Yt(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function oa(e){let t=E(e);return{value:D(t,`value`),label:D(t,`label`),...N(`description`,O(t,`description`))}}function sa(e){return e===void 0?{}:{session:ln(e)}}function ca(e){if(E(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function la(e){let t=E(e);return j(ua)(t.attachments)}function ua(e){let t=E(e);return{path:D(t,`path`),mimeType:D(t,`mimeType`),size:k(t,`size`)}}function da(e){if(E(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function fa(e){if(E(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function pa(e){if(E(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function ma(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:Yt(t.sessionIds,`sessionIds`),r=M(t,`archivedCount`),i=M(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function ha(e){if(E(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function ga(e){if(E(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function _a(e){if(E(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function va(e){if(E(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function ya(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEBUI ${t} field`);return n}}function M(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function ba(e,t){let n=e[t];if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected number|null field: ${t}`);return n}function N(e,t){return t===void 0?{}:{[e]:t}}function xa(e){let t=E(e),n=E(t.memory),r=E(t.network);return{generatedAt:D(t,`generatedAt`),memory:{totalBytes:k(n,`totalBytes`),usedBytes:k(n,`usedBytes`),freeBytes:k(n,`freeBytes`),usagePercent:k(n,`usagePercent`)},network:wa(r)}}function Sa(e){let t=E(e),n=E(t.os),r=E(t.cpu),i=E(t.memory),a=E(t.network),o=t.gpu,s;if(o!=null){let e=E(o),t={name:D(e,`name`)},n=O(e,`driverVersion`);n!==void 0&&(t.driverVersion=n);let r=M(e,`memoryTotalBytes`);r!==void 0&&(t.memoryTotalBytes=r);let i=M(e,`memoryUsedBytes`);i!==void 0&&(t.memoryUsedBytes=i);let a=M(e,`utilizationPercent`);a!==void 0&&(t.utilizationPercent=a);let c=M(e,`temperatureCelsius`);c!==void 0&&(t.temperatureCelsius=c),s=t}let c={generatedAt:D(t,`generatedAt`),os:{platform:D(n,`platform`),release:D(n,`release`),arch:D(n,`arch`),uptimeSeconds:k(n,`uptimeSeconds`)},cpu:{model:D(r,`model`),cores:k(r,`cores`),usagePercent:k(r,`usagePercent`)},memory:{totalBytes:k(i,`totalBytes`),usedBytes:k(i,`usedBytes`),freeBytes:k(i,`freeBytes`),usagePercent:k(i,`usagePercent`)},network:Ca(a)};s!==void 0&&(c.gpu=s);let l=O(t,`piVersion`);l!==void 0&&(c.piVersion=l);let u=O(t,`piWebUiVersion`);return u!==void 0&&(c.piWebUiVersion=u),c}function Ca(e){let t={hostname:D(e,`hostname`),localIpv4Addresses:Yt(e.localIpv4Addresses,`localIpv4Addresses`),...wa(e)},n=O(e,`publicIpv4`);n!==void 0&&(t.publicIpv4=n);let r=O(e,`publicIpv6`);return r!==void 0&&(t.publicIpv6=r),t}function wa(e){let t={},n=M(e,`downloadSpeedBytesPerSecond`);n!==void 0&&(t.downloadSpeedBytesPerSecond=n);let r=M(e,`uploadSpeedBytesPerSecond`);return r!==void 0&&(t.uploadSpeedBytesPerSecond=r),t}function Ta(e){return typeof e==`string`?e:e.id}function Ea(e){return typeof e==`string`?void 0:e.cwd}function Da(e,t,n,r){let i=new URLSearchParams;r?.path!==void 0&&i.set(`path`,r.path),r?.staged===!0&&i.set(`staged`,`true`);let a=i.toString();return`api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/git/diff${a?`?${a}`:``}`}function Oa(e,t,n=`local`){let r=new URLSearchParams,i=Ea(e);i!==void 0&&i!==``&&r.set(`cwd`,i),t?.limit!==void 0&&r.set(`limit`,String(t.limit)),t?.before!==void 0&&r.set(`before`,String(t.before));let a=r.toString();return`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(Ta(e))}/messages${a===``?``:`?${a}`}`}function ka(e,t=`local`){let n=new URLSearchParams,r=Ea(e);r!==void 0&&r!==``&&n.set(`cwd`,r);let i=n.toString();return`api/machines/${encodeURIComponent(t)}/sessions/${encodeURIComponent(Ta(e))}/export${i===``?``:`?${i}`}`}function Aa(e,t,n,r){let i=new URLSearchParams({path:n});return r?.createDirs===!1&&i.set(`createDirs`,`false`),r?.overwrite===!1&&i.set(`overwrite`,`false`),bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function ja(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var P=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function Ma(e){return typeof e==`string`?e:e.id}function Na(e){return typeof e==`string`?void 0:e.cwd}function Pa(e,t=`local`){return`${P(t)}/sessions/${encodeURIComponent(Ma(e))}`}function F(e,t,n=`local`){return`${Pa(e,n)}/${t}`}function Fa(e,t,n=`local`){return`${F(e,t,n)}${La(e)}`}function Ia(e,t=`local`){return`${Pa(e,t)}${La(e)}`}function La(e){let t=Na(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function I(e,t={}){let n=Na(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Ra(e){return JSON.stringify({sessions:e.map(za)})}function za(e){let t=Ma(e),n=Na(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Ba(e){return e===`local`?`api/pi-webui/status`:`${P(e)}/pi-webui/status`}var Va={piWebUiStatus:(e=`local`)=>w(Ba(e),Li),checkForUpdates:(e=`local`)=>w(`${Ba(e)}?refresh=1`,Li,{cache:`no-store`}),piWebUiRuntime:()=>w(`api/pi-webui/runtime`,Ri),systemInfo:(e=`local`)=>w(`${P(e)}/pi-webui/system-info`,Sa),systemMetrics:(e=`local`)=>w(`${P(e)}/pi-webui/system-metrics`,xa,{cache:`no-store`})},Ha={machines:()=>w(`api/machines`,$t),addMachine:e=>w(`api/machines`,en,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>w(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>w(`api/machines/${encodeURIComponent(e)}/health`,tn),runtime:(e,t=!1)=>w(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,nn,t?{cache:`no-store`}:{})};function Ua(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${P(t)}/agent-memory/snapshot?${n.toString()}`}var Wa={snapshot:(e,t=`local`)=>w(Ua(e,t),Xt,{cache:`no-store`})};function Ga(e){return e===void 0?`api/config`:`${P(e)}/config`}function Ka(e){return e===void 0?`api/plugins`:`${P(e)}/plugins`}var qa={config:e=>w(Ga(e),si),saveConfig:(e,t)=>w(Ga(t),si,{method:`PUT`,body:JSON.stringify({config:e})})},Ja={plugins:e=>w(Ka(e),Ni)};function Ya(e=`local`){return`${P(e)}/models-config`}var Xa={config:(e=`local`)=>w(Ya(e),tr),save:(e,t=`local`)=>w(Ya(t),lr,{method:`PUT`,body:JSON.stringify(e)}),test:(e,t=`local`)=>w(`${Ya(t)}/test`,fr,{method:`POST`,body:JSON.stringify(e)}),discover:(e,t=`local`)=>w(`${Ya(t)}/discover`,ur,{method:`POST`,body:JSON.stringify(e)})};function Za(e=`local`){return`${P(e)}/skills`}function Qa(e,t=`local`){return`${Za(t)}?${new URLSearchParams({cwd:e}).toString()}`}var $a={list:(e,t=`local`)=>w(Qa(e,t),pr),toggle:(e,t=`local`)=>w(Za(t),_r,{method:`PATCH`,body:JSON.stringify(e)}),search:(e,t=`local`)=>w(`${Za(t)}/search`,vr,{method:`POST`,body:JSON.stringify(e)}),install:(e,t=`local`)=>w(`${Za(t)}/install`,_r,{method:`POST`,body:JSON.stringify(e)}),check:(e,t=`local`)=>w(`${Za(t)}/check`,br,{method:`POST`,body:JSON.stringify(e)}),update:(e,t=`local`)=>w(`${Za(t)}/update`,Cr,{method:`POST`,body:JSON.stringify(e)})};function eo(e=``,t){let n=t===void 0?`api/pi-packages`:`${P(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var to={packages:e=>w(eo(``,e),bi),install:(e,t)=>{let n={source:e};return w(eo(`install`,t),xi,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return w(eo(`remove`,n),xi,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return w(eo(`update`,t),xi,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}};function no(e=`local`){return`${P(e)}/package-plugins`}function ro(e,t=`local`){return`${no(t)}?${new URLSearchParams({cwd:e}).toString()}`}var io={list:(e,t=`local`)=>w(ro(e,t),Ti),mutate:(e,t=`local`)=>w(no(t),Ti,{method:`POST`,body:JSON.stringify(e)})},ao={workspaceActivity:(e=`local`)=>w(`${P(e)}/activity`,oi)},oo={projects:(e=`local`)=>w(`${P(e)}/projects`,j(on)),addProject:(e,t,n,r=`local`)=>w(`${P(r)}/projects`,on,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>w(`${P(t)}/projects/${encodeURIComponent(e)}`,da,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>w(`${P(t)}/project-directories?q=${encodeURIComponent(e)}`,j(Ur))},so={workspaces:(e,t=`local`)=>w(`${P(t)}/projects/${encodeURIComponent(e)}/workspaces`,j(sn)),deleteWorkspace:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ni,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,Wr),workspaceFile:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,Kr),writeWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({path:n});i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!1&&o.set(`overwrite`,`false`);let s=r instanceof Uint8Array,c=s?new Uint8Array(r):new TextEncoder().encode(r);return w(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,qr,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})},deleteWorkspaceFile:(e,t,n,r=`local`)=>{let i=new URLSearchParams({path:n});return w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,Jr,{method:`DELETE`})},moveWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({fromPath:n,toPath:r});return i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!0&&o.set(`overwrite`,`true`),w(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,Yr,{method:`POST`})}},co={sessions:(e,t=`local`)=>w(`${P(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(ln)),unreadCatalog:(e=`local`)=>w(`${P(e)}/sessions/unread`,_n,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return w(F(e,`unread/acknowledge`,r),_n,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>w(Fa(e,`notifications`,t),wn),dismissNotification:(e,t,n,r=`local`)=>w(F(e,`notifications/dismiss`,r),wn,{method:`POST`,body:I(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>w(F(e,`notifications/dismiss-all`,r),wn,{method:`POST`,body:I(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`)=>w(`${P(t)}/sessions`,ln,{method:`POST`,body:JSON.stringify({cwd:e})}),sessionDefaults:(e,t=`local`)=>w(`${P(t)}/session-defaults?cwd=${encodeURIComponent(e)}`,er),updateSessionDefaults:(e,t,n=`local`)=>w(`${P(n)}/session-defaults`,er,{method:`PUT`,body:JSON.stringify({cwd:e,...t})}),cleanupPreview:(e,t=`local`)=>w(`${P(t)}/sessions/cleanup/preview`,Vn,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>w(`${P(t)}/sessions/cleanup`,Hn,{method:`POST`,body:JSON.stringify(e)}),forceCleanup:(e=`local`)=>w(`${P(e)}/sessions/cleanup/force`,Hn,{method:`POST`}),archiveMany:(e,t=`local`)=>w(`${P(t)}/sessions/bulk/archive`,Un,{method:`POST`,body:Ra(e)}),deleteArchivedMany:(e,t=`local`)=>w(`${P(t)}/sessions/bulk/delete-archived`,Wn,{method:`POST`,body:Ra(e)}),messages:(e,t,n=`local`)=>w(Oa(e,t,n),Qt),status:(e,t=`local`)=>w(Fa(e,`status`,t),mn),systemPrompt:(e,t=`local`)=>w(Fa(e,`system-prompt`,t),gn),streamSnapshot:(e,t=`local`)=>w(Fa(e,`stream-snapshot`,t),hn),clearQueue:(e,t=`local`)=>w(F(e,`queue/clear`,t),mn,{method:`POST`,body:I(e)}),dismissWarning:(e,t,n=`local`)=>w(F(e,`warnings/dismiss`,n),mn,{method:`POST`,body:I(e,{dismissId:t})}),models:(e,t=`local`)=>w(Fa(e,`models`,t),$n),setModel:(e,t,n,r=`local`)=>w(F(e,`model`,r),mn,{method:`POST`,body:I(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>w(F(e,`model/cycle`,n),mn,{method:`POST`,body:I(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>w(Fa(e,`thinking-levels`,t),Tr),setThinkingLevel:(e,t,n=`local`)=>w(F(e,`thinking-level`,n),mn,{method:`POST`,body:I(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>w(F(e,`thinking-level/cycle`,t),mn,{method:`POST`,body:I(e)}),commands:(e,t=`local`)=>w(Fa(e,`commands`,t),j(Hr)),prompt:(e,t,n,r=`local`,i)=>w(F(e,`prompt`,r),ca,{method:`POST`,body:I(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>w(F(e,`attachments`,n),la,{method:`POST`,body:I(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>w(F(e,`shell`,n),ca,{method:`POST`,body:I(e,{text:t})}),runCommand:(e,t,n=`local`)=>w(F(e,`commands/run`,n),Xi,{method:`POST`,body:I(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>w(F(e,`commands/respond`,r),Xi,{method:`POST`,body:I(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>w(F(e,`tree/navigate`,n),ea,{method:`POST`,body:I(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),editFromHere:(e,t,n=`local`)=>w(F(e,`messages/edit-from-here`,n),ea,{method:`POST`,body:I(e,{entryId:t})}),forkFromHere:(e,t,n=`local`)=>w(F(e,`messages/fork`,n),ta,{method:`POST`,body:I(e,{entryId:t})}),abort:(e,t=`local`)=>w(F(e,`abort`,t),fa,{method:`POST`,body:I(e)}),stop:(e,t=`local`)=>w(F(e,`stop`,t),pa,{method:`POST`,body:I(e)}),archive:(e,t=`local`)=>w(F(e,`archive`,t),ma,{method:`POST`,body:I(e)}),archiveWithDescendants:(e,t=`local`)=>w(F(e,`archive-tree`,t),ma,{method:`POST`,body:I(e)}),restore:(e,t=`local`)=>w(F(e,`restore`,t),ha,{method:`POST`,body:I(e)}),deleteArchived:(e,t=`local`)=>w(Ia(e,t),ga,{method:`DELETE`}),detachParent:(e,t=`local`)=>w(F(e,`detach-parent`,t),_a,{method:`POST`,body:I(e)}),reloadSession:(e,t=`local`)=>w(F(e,`reload`,t),va,{method:`POST`,body:I(e)}),pin:(e,t=`local`)=>w(F(e,`pin`,t),ln,{method:`POST`,body:I(e)}),unpin:(e,t=`local`)=>w(F(e,`unpin`,t),ln,{method:`POST`,body:I(e)}),authProviders:e=>{let t=new URLSearchParams;e?.mode!==void 0&&t.set(`mode`,e.mode),e?.authType!==void 0&&t.set(`authType`,e.authType);let n=t.toString();return w(`${P(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,Ar)},saveApiKey:(e,t,n=`local`)=>w(`${P(n)}/auth/api-key`,ca,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>w(`${P(t)}/auth/api-key/interactive`,jr,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>w(`${P(t)}/auth/logout`,ca,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>w(`${P(t)}/auth/oauth`,jr,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>w(`${P(t)}/auth/oauth/${encodeURIComponent(e)}`,jr),respondOAuthFlow:(e,t,n,r=`local`)=>w(`${P(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,jr,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>w(`${P(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,jr,{method:`POST`})},lo={terminals:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(ti)),startTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ti,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,da,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,da,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,ti,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ni,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>w(`${P(t)}/terminal-command-runs${fo(e)}`,j(ni)),getCommandRun:(e,t=`local`)=>uo(e,t),cancelCommandRun:(e,t=`local`)=>w(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ni,{method:`POST`})};async function uo(e,t){let n=await fetch(bt(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(po(e)??n.statusText)}return ni(await n.json())}}function fo(e){if(e===void 0)return``;let 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));let n=t.toString();return n===``?``:`?${n}`}function po(e){if(!mo(e))return;let t=e.error;return typeof t==`string`?t:void 0}function mo(e){return typeof e==`object`&&!!e}var ho={files:(e,t,n={})=>{let r=new URLSearchParams({q:t});return n.kind!==void 0&&r.set(`kind`,n.kind),n.mode!==void 0&&r.set(`mode`,n.mode),n.scope!==void 0&&r.set(`scope`,n.scope),n.workspaceScoped===!0&&n.projectId!==void 0&&n.workspaceId!==void 0?w(`${P(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,j(Ur)):(r.set(`cwd`,e),w(`${P(n.machineId)}/files?${r.toString()}`,j(Ur)))}},go={gitStatus:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Zr),gitDiff:(e,t,n,r=`local`)=>w(Da(r,e,t,n),ei)},L={...Va,...Ha,...Wa,...qa,...Ja,...to,...io,...ao,...oo,...so,...co,...lo,...ho,...go};function _o(e,t=`local`){let n=typeof e==`string`?void 0:e.cwd,r=n===void 0||n===``?``:`?${new URLSearchParams({cwd:n}).toString()}`,i=typeof e==`string`?e:e.id;return new WebSocket(xt(`${bo(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function vo(e,t,n,r,i=`local`){let a=r===void 0?``:`?${new URLSearchParams({cols:String(r.cols),rows:String(r.rows)}).toString()}`;return new WebSocket(xt(`${bo(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function yo(e=`local`){return new WebSocket(xt(`${bo(e)}/events`))}function bo(e){return`api/machines/${encodeURIComponent(e)}`}var xo=`.pi-webui/uploads`,So=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},Co=class extends Error{constructor(e,t){super(Po(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function wo(e){return e?.uploads?.defaultFolder??`.pi-webui/uploads`}function To(e,t){return e?.uploads?.defaultFolder??t}function Eo(e,t){let n=Lo(e,`upload destination`,{allowEmpty:!0}),r=Lo(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function Do(e,t,n,r={}){let i=r.xhrFactory?.()??new XMLHttpRequest,a=!1,o=!1;return{promise:new Promise((s,c)=>{let l=e=>{a||(a=!0,c(e))},u=e=>{a||(a=!0,s(e))};i.open(`PUT`,Aa(e,t,n.path,Ao(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(jo(e,n.file.size))},i.onload=()=>{if(i.status>=200&&i.status<300){try{r.onProgress?.({loaded:n.file.size,total:n.file.size,percent:1,lengthComputable:!0}),u(qr(zo(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Bo(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new So(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function Oo(e,t,n,r={}){let i=r.destinationFolder??`.pi-webui/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:Eo(i,e.name),loaded:0,total:e.size,percent:No(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(Mo(a,s,a.every(e=>e.done)))};return{promise:(async()=>{let i=[],u=[];for(let d=0;d<n.length;d+=1){if(c.requested)throw new So;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=Do(e,t,{path:p.path,file:f},{...ko(r),onProgress:e=>{p.total=e.total,p.loaded=Math.min(e.loaded,p.total),p.percent=e.percent,p.lengthComputable=e.lengthComputable,l()}});try{let e=await o.promise;p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,i.push(e),l()}catch(e){if(Io(e,c))throw e;let t=Fo(e);p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,p.error=t,u.push({index:d,name:f.name,path:p.path,error:t}),l()}finally{o=void 0}}}if(u.length>0)throw new Co(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function ko(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Ao(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function jo(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:No(e.loaded,n),lengthComputable:e.lengthComputable}}function Mo(e,t,n){let r=e.reduce((e,t)=>e+t.total,0),i=e.reduce((e,t)=>e+t.loaded,0);return{currentFileIndex:t,files:e.map(e=>({...e})),loaded:i,total:r,percent:No(i,r),done:n}}function No(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Po(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function Fo(e){return e instanceof Error?e.message:String(e)}function Io(e,t){return t.requested||e instanceof So}function Lo(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Ro(r))throw Error(`${t} must be workspace-relative`);let i=r.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(i.length===0){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(i.some(e=>e===`..`))throw Error(`${t} must not contain path traversal`);return i.join(`/`)}function Ro(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function zo(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Bo(e){let t=Vo(e);return Ho(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Vo(e){try{return zo(e)}catch{return}}function Ho(e){return typeof e==`object`&&!!e}function Uo(){return{sessions:[],projectSessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingSessions:!1,selectedNotificationInbox:void 0,treeDialog:void 0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,memory:{kind:`loading`},selectedTerminalId:void 0,error:``}}function Wo(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],projectSessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,isLoadingSessions:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:`core:workspace.files`,mainView:`chat`,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,memory:{kind:`loading`},activeTerminalCount:0,selectedTerminalId:void 0,piWebUiStatus:void 0,error:``}}function Go(e,t){return t?.phase===`active`||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Ko(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function qo(e,t){return`${e}:${t}`}function Jo(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var Yo=class{constructor(){this.pendingByKey=new Map}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.started&&(n.trailing=!0),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,started:!1,trailing:!1};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1;let n=r.latestRefresh;r.started=!0,t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}},Xo=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Yo,this.api=n.api??ao,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Zo(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=Qo(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...R(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Zo(e){let t={};for(let n of e.workspaces)Ko(n)&&(t[n.cwd]=n);return t}function Qo(e,t){let n={...e};return Ko(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var $o=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??L,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=ts(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){if(e!==void 0&&e!==``){await this.openLoginProvider(e);return}this.setState({authDialog:{step:`method`}})}async chooseLoginMethod(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,authType:e,machineId:R(this.getState())});this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:t}})}catch(e){this.setState({error:String(e)})}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:`API key is required`}});return}let n={...e};delete n.error,this.setState({authDialog:{...n,saving:!0}});try{await this.api.saveApiKey(e.provider.id,t,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(t){this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){try{let{providers:t}=await this.api.authProviders({mode:`logout`,machineId:R(this.getState())});if(e!==void 0&&e!==``){let n=t.find(t=>t.id===e);n!==void 0&&!this.rejectRemoteOAuth(`logout`,n)?await this.logoutProvider(n.id):n===void 0&&this.setState({error:`No stored credentials for ${e}`});return}this.setState({authDialog:{step:`logout`,providers:t}})}catch(e){this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog,n=t?.step===`logout`?t.providers.find(t=>t.id===e):void 0;if(!(n!==void 0&&this.rejectRemoteOAuth(`logout`,n)))try{await this.api.logoutProvider(e,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(e){this.setState({error:String(e)})}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId,o=e??t.inputValue??``,s={...t};delete s.error,this.setState({authDialog:{...s,responding:!0}});try{let e=await this.api.respondOAuthFlow(i,a,o,t.machineId),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||es(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||es(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.machineId;this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}closeDialog(){this.oauthOperationGeneration+=1,this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,machineId:R(this.getState())}),n=t.filter(t=>t.id===e);if(n.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(n.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:n}});return}let r=n[0];if(r===void 0)return;r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}})}catch(e){this.setState({error:String(e)})}}async startLoginFlow(e){if(this.rejectRemoteOAuth(`login`,e))return;let t=++this.oauthOperationGeneration;this.stopPolling();try{let n=R(this.getState()),r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,n):await this.api.startInteractiveApiKeyLogin(e.id,n);if(t!==this.oauthOperationGeneration){if(r.status===`running`)try{await this.api.cancelOAuthFlow(r.flowId,n)}catch{}return}this.updateOAuthFlow(r,n),r.status===`running`&&this.startPolling(r.flowId,n)}catch(e){t===this.oauthOperationGeneration&&this.setState({error:String(e)})}}rejectRemoteOAuth(e,t){let n=this.getState().selectedMachine;if(t.authType!==`oauth`||n?.kind!==`remote`)return!1;let r=n.baseUrl??`that remote PI WEBUI instance`;return this.setState({error:`OAuth ${e} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&(this.oauthOperationGeneration+=1,this.stopPolling());let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?es(n.flow):void 0,a=es(e),o=i!==void 0&&i===a,s=o?r:``,c=o&&n?.step===`oauth`?n.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,machineId:t,inputValue:s,responding:c}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i?.machineId!==t){this.stopPolling();return}let a=es(i.flow);try{let i=await this.api.oauthFlow(e,t),o=this.currentOAuthDialog(n,e);if(i.flowId!==e||r!==this.pollGeneration||o?.machineId!==t||es(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||es(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e=R(this.getState())){let t=this.selectedSessionForMachine(e);if(t!==void 0)try{let n=await this.api.status(t,e),r=this.selectedSessionForMachine(e);if(r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(R(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function es(e){return e.prompt?.requestId??e.select?.requestId}function ts(e){let t=e.trim(),n=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(n===null)return;let r=n[1];if(r!==`login`&&r!==`logout`)return;let i=n[2];return i===void 0||i===``?{command:r}:{command:r,providerId:i}}function ns(e){return e.replaceAll(`:`,`.`)}function rs(e){let t=new URLSearchParams(window.location.search),n=`${e}--`,r={};for(let[e,i]of t.entries()){if(!e.startsWith(n))continue;let t=e.slice(n.length),a=r[t];a===void 0?r[t]=i:Array.isArray(a)?a.push(i):r[t]=[a,i]}return r}function is(e,t){let n=rs(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function as(e,t,n,r){let i=new URL(window.location.href),a=`${e}--${t}`;if(i.searchParams.delete(a),n!=null&&n!==``)if(Array.isArray(n))for(let e of n)i.searchParams.append(a,String(e));else i.searchParams.set(a,String(n));os(i,r)}function os(e,t){`${e.pathname}${e.search}${e.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,e):window.history.pushState({},``,e))}function ss(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:Eo(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:ps(0,r),lengthComputable:!0,status:n===0?`uploading`:`pending`}}),n=t.reduce((e,t)=>e+t.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:n,percent:ps(0,n),status:`uploading`,startedAt:e.startedAt}}function cs(e,t){let n=new Map(t.files.map(e=>[e.index,e])),r=e.files.map(e=>{let r=n.get(e.index);if(r===void 0)return e;let i={...e,path:r.path,loaded:r.loaded,total:r.total,percent:r.percent,lengthComputable:r.lengthComputable,status:r.error===void 0?r.done?`completed`:t.currentFileIndex===e.index?`uploading`:e.status:`error`};return r.error===void 0?delete i.error:i.error=r.error,i});return{...e,files:r,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function ls(e,t,n){let r=e.files.map((e,n)=>{let r=t[n];return{...e,...r===void 0?{}:{path:r.path,response:r},loaded:e.total,percent:1,lengthComputable:!0,status:`completed`}}),i=fs(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function us(e,t,n){let r=e.files.map(n=>n.status===`completed`||n.status===`error`?n:n.status===`uploading`||n.index===e.currentFileIndex?{...n,status:`error`,error:t}:{...n,status:`cancelled`,error:`Not uploaded because an earlier file failed.`});return{...e,files:r,...fs(r),status:`error`,error:t,completedAt:n}}function ds(e,t){let n=`Upload cancelled`,r=e.files.map(e=>e.status===`completed`||e.status===`error`?e:{...e,status:`cancelled`,error:n});return{...e,files:r,...fs(r),status:`cancelled`,error:n,completedAt:t}}function fs(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function ps(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var ms=ns(`core:workspace.files`),hs=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??L,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Oo,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=R(this.getState()),r=await this.api.workspaceTree(e.id,t.id,``,n),i={...this.getState().expandedDirs};await Promise.all(Object.keys(i).map(async r=>{i[r]=(await this.api.workspaceTree(e.id,t.id,r,n)).entries})),this.setState({fileTree:r.entries,expandedDirs:i,fileTreeStale:!1,error:``})}catch(e){this.setState({error:String(e)})}}async expandDir(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:ys(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,R(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:``})}catch(e){this.setState({error:String(e)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),as(ms,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{let r=await this.api.workspaceFile(t.id,n.id,e,R(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(gs(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),as(ms,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)})}}}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`Select a workspace before uploading files.`});return}if(e.length===0)return;let i=R(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=ss({id:this.createUploadBatchId(),projectId:n.id,workspaceId:r.id,machineId:i,destinationFolder:t.destinationFolder,overwrite:a,createDirs:o,files:e,startedAt:this.now()})}catch(e){this.setState({error:String(e)});return}this.setUploadBatch(s);let c;try{c=this.uploadWorkspaceFiles(n.id,r.id,e,{destinationFolder:t.destinationFolder,machineId:i,overwrite:a,createDirs:o,onProgress:e=>{this.updateUploadProgress(s.id,e)}})}catch(e){return this.failUploadBatch(s.id,e),{batchId:s.id,done:Promise.resolve()}}this.uploadTasks.set(s.id,c);let l=c.promise.then(async e=>{await this.completeUploadBatch(s.id,e,t)}).catch(async e=>{await this.handleUploadFailure(s.id,e,t)}).finally(()=>{this.uploadTasks.delete(s.id)});return{batchId:s.id,done:l}}cancelWorkspaceUpload(e){let t=this.getUploadBatch(e);t?.status===`uploading`&&(this.setUploadBatch(ds(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:ys(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(cs(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(ls(r,t,this.now()),{error:``}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();let i=t[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}async handleUploadFailure(e,t,n){let r=this.failUploadBatch(e,t);if(!(t instanceof Co)||t.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();let i=t.responses[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}failUploadBatch(e,t){let n=this.getUploadBatch(e);if(n?.status!==`uploading`)return;if(_s(t)){let e=ds(n,this.now());return this.setUploadBatch(e),e}let r=vs(t),i=us(n,r,this.now());return this.setUploadBatch(i,{error:r}),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e,t={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e},...t})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&R(t)===e.machineId}};function gs(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function _s(e){return e instanceof So}function vs(e){return e instanceof Error?e.message:String(e)}function ys(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var bs=ns(`core:workspace.git`),xs=class{constructor(e,t,n){this.getState=e,this.setState=t,this.updateUrl=n,this.statusRequest=0,this.diffRequest=0}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0,this.pollingScope=void 0,this.statusRequest+=1,this.diffRequest+=1}async refreshGit(e={}){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(this.getState()),i=++this.statusRequest;this.diffRequest+=1;try{let a=await L.gitStatus(t.id,n.id,r);if(i!==this.statusRequest||!this.isCurrentWorkspace(t,n,r))return;this.setState({gitStatus:a,gitStale:!1,...e.reportError===!1?{}:{error:``}});let o=this.getState().selectedDiffPath;o!==void 0&&(a.files.some(e=>e.path===o)?await this.refreshDiff(o,e):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),as(bs,`diff`,void 0,{replace:!0})))}catch(a){if(i!==this.statusRequest||!this.isCurrentWorkspace(t,n,r))return;e.reportError!==!1&&this.setState({error:String(a)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:`core:workspace.git`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.git`}),as(bs,`diff`,e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e,t={}){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0)return;let i=R(this.getState()),a=++this.diffRequest;try{let[o,s]=await Promise.all([L.gitDiff(n.id,r.id,{path:e},i),L.gitDiff(n.id,r.id,{path:e,staged:!0},i)]);if(a!==this.diffRequest||!this.isCurrentWorkspace(n,r,i))return;this.setState({selectedDiff:o,selectedStagedDiff:s,...t.reportError===!1?{}:{error:``}})}catch(e){if(a!==this.diffRequest||!this.isCurrentWorkspace(n,r,i))return;t.reportError!==!1&&this.setState({error:String(e)})}}updatePolling(){let e=this.currentPollingScope();e===this.pollingScope&&this.pollTimer!==void 0||(this.dispose(),e!==void 0&&(this.pollingScope=e,this.refreshGit({reportError:!1}),this.pollTimer=window.setInterval(()=>{this.refreshGit({reportError:!1})},8e3)))}currentPollingScope(){let e=this.getState();if(!(e.selectedProject===void 0||e.selectedWorkspace?.isGitRepo!==!0))return JSON.stringify([R(e),e.selectedProject.id,e.selectedWorkspace.id])}isCurrentWorkspace(e,t,n){let r=this.getState();return R(r)===n&&r.selectedProject?.id===e.id&&r.selectedWorkspace?.id===t.id&&r.selectedWorkspace.projectId===t.projectId}},Ss=3e4,Cs={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},ws=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??Wa.snapshot,this.timer=n.timer??Cs,this.pollIntervalMs=n.pollIntervalMs??Ss}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}if(this.scope?.key!==t.key){this.startScope(t);return}this.inFlight?.generation===this.generation&&this.inFlight.scopeKey===t.key||this.pollTimer===void 0&&this.startRequest(t)}async refresh(){if(!this.observing)return;let e=this.currentScope();if(e===void 0){this.invalidateScope();return}if(this.scope?.key!==e.key){await this.startScope(e);return}this.clearPollTimer(),await this.startRequest(e)}dispose(){this.observing=!1,this.invalidateScope()}startScope(e){return this.invalidateScope(),this.scope=e,this.setState({memory:{kind:`loading`}}),this.startRequest(e)}startRequest(e){let t=this.inFlight;if(t?.generation===this.generation&&t.scopeKey===e.key)return t.promise;let n=this.generation,r=++this.nextRequestId,i={generation:n,requestId:r,scopeKey:e.key,promise:Promise.resolve()};this.inFlight=i;let a=this.load(e,n,r);return i.promise=a,a}async load(e,t,n){try{let n=await this.fetchSnapshot(e.workspacePath,e.machineId);if(!this.isCurrent(e,t))return;let r=Ts(n);this.setState({memory:r}),r.kind===`unavailable`&&this.stopObserving()}catch(n){if(!this.isCurrent(e,t))return;this.applyFailure(String(n))}finally{let r=this.inFlight?.requestId===n;r&&(this.inFlight=void 0),r&&this.isCurrent(e,t)&&this.scheduleNext(e,t)}}applyFailure(e){let t=this.getState().memory;if(t.kind===`data`){this.setState({memory:{...t,refreshError:e}});return}this.setState({memory:{kind:`error`,message:e}})}scheduleNext(e,t){this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.observing||!this.isCurrent(e,t))&&this.startRequest(e)},this.pollIntervalMs)}stopObserving(){this.observing&&(this.observing=!1,this.invalidateScope())}invalidateScope(){this.clearPollTimer(),this.scope=void 0,this.inFlight=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}currentScope(){let e=this.getState(),t=e.selectedProject,n=e.selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(e);return{key:JSON.stringify([r,t.id,n.id,n.path]),machineId:r,projectId:t.id,workspaceId:n.id,workspacePath:n.path}}isCurrent(e,t){if(!this.observing||t!==this.generation||this.scope?.key!==e.key)return!1;let n=this.currentScope();return n?.machineId===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.workspacePath===e.workspacePath}};function Ts(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalEntries:e.globalEntries,projectEntries:e.projectEntries,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}function Es(e){let t=[],n=[];for(let r of e)Ms(r.index)&&t.push(js(r,`staged`,r.index)),Ns(r.workingTree)&&n.push(js(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function Ds(e){let t=Es(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function Os(e){switch(e){case`modified`:return`M`;case`added`:return`A`;case`deleted`:return`D`;case`renamed`:return`R`;case`copied`:return`C`;case`untracked`:return`?`;case`conflicted`:return`U`;case`ignored`:return`!`;case`unmodified`:return``}}function ks(e){switch(e){case`modified`:return`Modified`;case`added`:return`Added`;case`deleted`:return`Deleted`;case`renamed`:return`Renamed`;case`copied`:return`Copied`;case`untracked`:return`Untracked`;case`conflicted`:return`Conflicted`;case`ignored`:return`Ignored`;case`unmodified`:return`Unmodified`}}function As(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function js(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function Ms(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function Ns(e){return e!==`unmodified`&&e!==`ignored`}var Ps=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await L.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:Is(this.getState().machineActivities,r),machineRuntimes:Is(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t)}catch(e){this.setState({error:String(e)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Uo()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){this.setState({error:``});try{let t=await L.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==t.id),t]}),await this.selectMachine(t),t}catch(e){this.setState({error:String(e)});return}}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`){this.setState({error:`The local machine cannot be removed.`});return}try{let n=this.getState().selectedMachine?.id===e.id;await L.deleteMachine(e.id);let r=this.getState().machines.filter(t=>t.id!==e.id),i=r.find(e=>e.id===`local`)??r[0];return this.setState({machines:r,machineStatuses:Fs(this.getState().machineStatuses,e.id),machineRuntimes:Fs(this.getState().machineRuntimes,e.id),machineActivities:Fs(this.getState().machineActivities,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(e){this.setState({error:String(e)});return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await L.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(e){this.setState({error:String(e)});return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await L.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.setState({error:String(n)});return}}async selectInitialMachine(e,t){let n=e.find(e=>e.id===(t??`local`));if(n===void 0)return this.localMachine(e);if(n.kind!==`remote`)return n;let r=await this.safeRemoteHealth(n);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${n.name} is unavailable; reconnecting…`}}),n}async safeRemoteHealth(e){try{return await L.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>L.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>L.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function Fs(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Is(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Ls=`~/workspace`,Rs=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??L,this.onProjectsApplied=r.onProjectsApplied}async loadProjects(){let e=R(this.getState());this.setState({error:``,isLoadingProjects:!0});try{let t=await this.api.projects(e);if(R(this.getState())!==e)return;let n;if(t.length===0){if(n=await this.api.addProject(Ls,void 0,!0,e),R(this.getState())!==e)return;t=[n]}let r=new Set(t.map(e=>e.id)),i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>r.has(e))),a=this.getState().selectedProject,o=a!==void 0&&t.some(e=>e.id===a.id&&e.path!==a.path);this.setState({projects:t,workspacesByProjectId:i}),o&&this.workspaces.clearSelection(),this.onProjectsApplied?.(e),n!==void 0&&await this.workspaces.selectProject(n)}catch(t){R(this.getState())===e&&this.setState({error:String(t)})}finally{R(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=R(this.getState());try{let r=await this.api.addProject(e.trim(),void 0,t,n);if(R(this.getState())!==n)return;let i=this.getState().projects;this.setState({projects:[...i.filter(e=>e.id!==r.id),r],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(r)}catch(e){R(this.getState())===n&&this.setState({error:String(e)})}}async closeProject(e){let t=R(this.getState());try{if(await this.api.closeProject(e,t),R(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){R(this.getState())===t&&this.setState({error:String(e)})}}},zs=5e3,Bs=`reconcile selected project catalog`,Vs={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},Hs=class{constructor(e,t){this.getState=e,this.generation=0,this.nextRequestId=0,this.observing=!1,this.listWorkspaces=t.workspaces??so.workspaces,this.applySnapshot=t.applySnapshot,this.timer=t.timer??Vs,this.pollIntervalMs=t.pollIntervalMs??zs,this.onBackgroundError=t.onBackgroundError,this.captureTopologyRequest=t.captureTopologyRequest}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}let n=this.retargetScope(t);this.inFlight===void 0&&(!n&&this.pollTimer!==void 0||this.scheduleNext(t,this.generation))}refresh(){if(!this.observing)return Promise.resolve();let e=this.currentScope();if(e===void 0)return this.invalidateScope(),Promise.resolve();this.retargetScope(e),this.clearPollTimer();let t=this.generation,n=this.inFlight;return n===void 0?this.startRequest(e,t):n.generation===t&&n.scopeKey===e.key?n.promise:this.queueImmediateRefresh(e,t)}dispose(){this.observing=!1,this.invalidateScope()}retargetScope(e){return this.scope?.key===e.key?(this.scope=e,!1):(this.clearPollTimer(),this.clearQueuedImmediateRefresh(),this.scope=e,this.generation+=1,!0)}startRequest(e,t){let n=this.inFlight;if(n!==void 0)return n.generation===t&&n.scopeKey===e.key?n.promise:this.queueImmediateRefresh(e,t);let r=++this.nextRequestId,i,a=new Promise(e=>{i=e});if(i===void 0)throw Error(`Project catalog request promise was not initialized`);return this.inFlight={generation:t,requestId:r,scopeKey:e.key,promise:a},this.load(e,t,r).then(i,i),a}async load(e,t,n){try{let n=this.captureTopologyRequest?.({machineId:e.machineId,projectId:e.project.id,projectPath:e.project.path}),r=await this.listWorkspaces(e.project.id,e.machineId);if(!this.isCurrent(e,t))return;await this.applySnapshot({machineId:e.machineId,project:e.project,workspaces:r,...n===void 0?{}:{topologyRequest:n}})}catch(n){this.isCurrent(e,t)&&this.reportBackgroundError(n)}finally{this.finishRequest(n)}}finishRequest(e){if(this.inFlight?.requestId!==e)return;this.inFlight=void 0;let t=this.queuedImmediateRefresh;if(t!==void 0){if(this.queuedImmediateRefresh=void 0,this.isCurrent(t.scope,t.generation)){this.startRequest(t.scope,t.generation).then(()=>{t.resolve()},()=>{t.resolve()});return}t.resolve()}let n=this.scope;n!==void 0&&this.isCurrent(n,this.generation)&&this.scheduleNext(n,this.generation)}queueImmediateRefresh(e,t){let n=this.queuedImmediateRefresh;if(n?.generation===t&&n.scope.key===e.key)return n.promise;this.clearQueuedImmediateRefresh();let r,i=new Promise(e=>{r=e});if(r===void 0)throw Error(`Queued project catalog refresh promise was not initialized`);return this.queuedImmediateRefresh={generation:t,scope:e,promise:i,resolve:r},i}scheduleNext(e,t){this.isCurrent(e,t)&&(this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.isCurrent(e,t)||this.inFlight!==void 0)&&this.startRequest(e,t)},this.pollIntervalMs))}stopObserving(){this.observing=!1,this.invalidateScope()}invalidateScope(){this.clearPollTimer(),this.clearQueuedImmediateRefresh(),this.scope=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}clearQueuedImmediateRefresh(){let e=this.queuedImmediateRefresh;this.queuedImmediateRefresh=void 0,e?.resolve()}currentScope(){let e=this.getState(),t=e.selectedProject;if(t===void 0||e.isLoadingWorkspaces)return;let n=R(e);return{key:JSON.stringify([n,t.id,t.path]),machineId:n,project:t}}isCurrent(e,t){return!this.observing||t!==this.generation||this.scope?.key!==e.key?!1:this.currentScope()?.key===e.key}reportBackgroundError(e){if(this.onBackgroundError!==void 0)try{this.onBackgroundError(Bs,e)}catch{}}};function Us(e,t){return t[e.path]}function Ws(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Gs(e,t,n){return Js(Ys(e,t,n))}function Ks(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function qs(e){return Js(Object.values(e??{}))}function Js(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Ys(e,t,n){return Object.values(n).filter(n=>Ks(e,t,n.cwd))}var Xs=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??so,this.onProjectTopology=n.onProjectTopology,this.captureTopologyRequest=n.captureTopologyRequest,this.onError=n.onError}handleActivityApplied(e){return R(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return R(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(R(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!Zs(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=this.captureTopologyRequest?.({machineId:e.machineId,projectId:t.id,projectPath:t.path}),r=await this.api.workspaces(t.id,e.machineId);await this.applyProjectWorkspaces(e,t,r,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!Zs(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(R(this.getState()))}async applyProjectWorkspaces(e,t,n,r){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let i=this.getState();if(i.projects.find(e=>e.id===t.id)?.path===t.path&&!(r===void 0&&i.workspacesByProjectId[t.id]!==t.startingWorkspaces)){if(this.onProjectTopology!==void 0){await this.onProjectTopology({machineId:e.machineId,projectId:t.id,projectPath:t.path,workspaces:n,...r===void 0?{}:{topologyRequest:r}});return}this.setState({workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:n}})}}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&R(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Ko).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function Zs(e,t,n){return e.some(e=>Ks(e,t[e.id]??[],n))}var Qs=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??Va,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=R(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebUiStatus(e);this.isCurrent(e,t)&&this.setState({piWebUiStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebUiStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=R(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebUiStatus:t}),$s(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return R(this.getState())===e&&t===this.requestSequence}};function $s(e){if(e.release.error!==void 0)throw Error(`PI WEBUI update check failed: ${e.release.error}`);if(e.release.skipped===!0)throw Error(`PI WEBUI update check was skipped because remote version checks are disabled by offline/version-check settings`)}var ec=`pi-webui:cached-new-sessions:v1`,tc=`browserCachedNew`,nc=`local`;function rc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function ic(e,t=nc,n=rc()){if(e.messageCount!==0||e.archived===!0)return;let r=uc(n).filter(n=>n.id!==e.id||n.machineId!==t);dc([ac(e,t),...r],n)}function ac(e,t=nc){return{...e,browserCachedNew:!0,machineId:t}}function oc(e,t=nc,n=rc()){dc(uc(n).filter(n=>n.id!==e||n.machineId!==t),n)}function sc(e,t,n=nc,r=rc()){let i=new Set(t.map(e=>e.id)),a=uc(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&dc(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function cc(e){return e!==void 0&&pc(e)&&e.browserCachedNew===!0}function lc(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},...`machineId`in e&&typeof e.machineId==`string`?{machineId:e.machineId}:{machineId:nc},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function uc(e=rc()){try{let t=e?.getItem(ec);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>fc(e)):[]}catch{return[]}}function dc(e,t=rc()){try{e.length===0?t?.removeItem(ec):t?.setItem(ec,JSON.stringify(e))}catch{}}function fc(e){if(!mc(e))return[];let t=hc(e,`id`),n=hc(e,`path`),r=hc(e,`cwd`),i=hc(e,`created`),a=hc(e,`modified`),o=hc(e,`firstMessage`),s=_c(e,`messageCount`);if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s!==0)return[];let c=gc(e,`name`),l=gc(e,`parentSessionPath`),u=gc(e,`machineId`)??nc;return[{id:t,path:n,cwd:r,...c===void 0?{}:{name:c},created:i,modified:a,messageCount:s,firstMessage:o,...l===void 0?{}:{parentSessionPath:l},machineId:u,browserCachedNew:!0}]}function pc(e){return tc in e}function mc(e){return typeof e==`object`&&!!e}function hc(e,t){let n=e[t];return typeof n==`string`?n:void 0}function gc(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function _c(e,t){let n=e[t];return typeof n==`number`?n:void 0}function vc(e){return Lc(e.flatMap(Cc)).filter(e=>e.parts.length>0)}function yc(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function bc(e,t){let n=kc(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=Kc(t,`canFork`);return{...e,...n===void 0?{}:{meta:n},...r===void 0?{}:{entryId:r},...i===void 0?{}:{previousAssistantEntryId:i},...a===void 0?{}:{canFork:a}}}function xc(e,t,n){if(n===``)return e;let r=e.at(-1),i=r?.parts.at(-1);return r?.role===t&&i?.type===`text`?[...e.slice(0,-1),{...r,parts:[...r.parts.slice(0,-1),{...i,text:i.text+n}]}]:r?.role===t?[...e.slice(0,-1),{...r,parts:[...r.parts,{type:`text`,text:n}]}]:[...e,yc(t,n)]}function Sc(e,t){if(t===``)return e;let n=e.at(-1),r=n?.parts.at(-1);return n?.role===`assistant`&&r?.type===`thinking`?[...e.slice(0,-1),{...n,parts:[...n.parts.slice(0,-1),{...r,text:r.text+t}]}]:n?.role===`assistant`?[...e.slice(0,-1),{...n,parts:[...n.parts,{type:`thinking`,text:t}]}]:[...e,{role:`assistant`,parts:[{type:`thinking`,text:t}]}]}function Cc(e){if(Tc(e))return[e];if(z(e,`role`)===`bashExecution`)return[bc(Mc(e),e)];let t=Nc(z(e,`role`)),n=Pc(Gc(e,`content`),e),r=t===`user`?Ec(n):void 0;if(r!==void 0)return r.map(t=>bc(t,e));let i=Oc(e);if(t===`tool`)return[bc({role:t,parts:n,...i===void 0?{}:{source:i}},e)];let a=n.filter(e=>e.type!==`empty`),o=t===`assistant`&&a.length>0&&a.every(e=>e.type===`skillRead`)?`skill`:t,s=a.length>0?[bc({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=wc(e);return c===void 0?s:[...s,bc(c,e)]}function wc(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return yc(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function Tc(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Gc(e,`parts`))}function Ec(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=Dc(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 Dc(e){let t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;let n=t[4]?.trim();return{name:t[1]??`skill`,location:t[2]??``,content:t[3]??``,...n===void 0||n===``?{}:{userMessage:n}}}function Oc(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function kc(e){let t=Ac(Gc(e,`timestamp`)),n=jc(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function Ac(e){if(typeof e==`number`&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!=`string`||e===``)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function jc(e){if(z(e,`role`)!==`assistant`)return;let t=z(e,`provider`),n=z(e,`model`),r=z(e,`responseModel`);if(!((t===void 0||t===``)&&(n===void 0||n===``)&&(r===void 0||r===``)))return{...t===void 0||t===``?{}:{provider:t},...n===void 0||n===``?{}:{id:n},...r===void 0||r===``?{}:{responseId:r}}}function Mc(e){let t=z(e,`command`)??``,n=Kc(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Gc(e,`output`);r!=null&&n.push(``,Jc(r));let i=Gc(e,`exitCode`);i!=null&&n.push(``,`exit ${Jc(i)}`),Kc(e,`cancelled`)===!0&&n.push(``,`cancelled`),Kc(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=z(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
4
4
  `)}]}}function Nc(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function Pc(e,t){return typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=z(e,`type`),n=z(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=z(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=z(e,`name`)??`tool`,n=Gc(e,`arguments`),r=z(e,`id`),i=t===`read`?Ic(z(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:Hc(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=z(e,`data`),n=z(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return Vc(e)}).map(e=>e.type===`text`&&z(t,`role`)===`toolResult`?Fc(e.text,t):e):Vc(e)}function Fc(e,t){let n=z(t,`toolCallId`),r=Gc(t,`content`),i=Gc(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:z(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:Kc(t,`isError`)===!0}}function Ic(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(!(n===void 0||n===``))return{name:n,path:e}}function Lc(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.entryId===void 0?{}:{entryId:r.entryId},...r.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:r.previousAssistantEntryId},...r.canFork===void 0?{}:{canFork:r.canFork},...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts){if(o.type===`toolCall`){a();let e=Rc(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0});continue}if(o.type===`toolResult`){let e=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(e!==void 0&&zc(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function Rc(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 zc(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=Bc(n.details)??i.preview,o={...i,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...a===void 0?{}:{preview:a}};return e[t.lineIndex]={...r,parts:[...r.parts.slice(0,t.partIndex),o,...r.parts.slice(t.partIndex+1)]},!0}function Bc(e){let t=Gc(e,`preview`);if(!Wc(t))return;let n=z(t,`diff`),r=z(t,`error`),i=qc(t,`firstChangedLine`);if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function Vc(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:Hc(e)}]:[{type:`text`,text:Jc(e)}]}function Hc(e){if(!Wc(e))return Jc(e);let t=z(e,`command`);if(t!==void 0)return t;let n=z(e,`path`);if(n!==void 0)return n;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return`edit text replacement`;let r=e.edits;return Array.isArray(r)?`${String(r.length)} edit${r.length===1?``:`s`}`:Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,t])=>`${e}: ${Uc(t)}`).join(` · `)}function Uc(e){return typeof e==`string`?e.length>80?`${e.slice(0,77)}…`:e:typeof e==`number`||typeof e==`boolean`?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?``:`s`}`:typeof e==`object`&&e?`object`:``}function Wc(e){return typeof e==`object`&&!!e}function Gc(e,t){return Wc(e)?e[t]:void 0}function z(e,t){let n=Gc(e,t);return typeof n==`string`?n:void 0}function Kc(e,t){let n=Gc(e,t);return typeof n==`boolean`?n:void 0}function qc(e,t){let n=Gc(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Jc(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Yc=`pi-webui:prompt-draft:`;function Xc(e){return`${Yc}${e}`}function Zc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Qc(e,t=Zc()){try{return t?.getItem(Xc(e))??``}catch{return``}}function $c(e,t,n=Zc()){try{t?n?.setItem(Xc(e),t):n?.removeItem(Xc(e))}catch{}}function el(e,t=Zc()){try{t?.removeItem(Xc(e))}catch{}}function tl(e,t,n=Zc()){let r=Qc(e,n);r!==``&&($c(t,r,n),el(e,n))}function nl(e,t){return yc(`bash`,`${t===!0?`excluded from context
@@ -608,10 +608,16 @@ This will delete every archived session on this machine regardless of age or cle
608
608
  .queued-heading { min-width: 0; flex: 1 1 180px; display: grid; gap: 2px; }
609
609
  .queued-heading strong { color: var(--pi-warning); }
610
610
  .queued-heading small { color: var(--pi-muted); }
611
- .queued-clear-button { flex: 0 0 auto; border: 1px solid var(--pi-warning-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-warning); padding: 5px 10px; font: 12px system-ui, sans-serif; white-space: nowrap; cursor: pointer; }
612
- .queued-clear-button:hover, .queued-clear-button:focus { border-color: var(--pi-warning); color: var(--pi-text-bright); }
611
+ .queued-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0 0 14px; }
612
+ .queued-action-button, .queued-clear-button { flex: 0 0 auto; border: 1px solid var(--pi-warning-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-warning); padding: 5px 10px; font: 12px system-ui, sans-serif; white-space: nowrap; cursor: pointer; }
613
+ .queued-action-button:hover, .queued-action-button:focus-visible, .queued-clear-button:hover, .queued-clear-button:focus-visible { border-color: var(--pi-accent); color: var(--pi-text-bright); }
614
+ .queued-action-button:focus-visible, .queued-clear-button:focus-visible { outline: 1px solid var(--pi-border); outline-offset: 2px; }
613
615
  .queued-message { display: grid; gap: 4px; padding-top: 8px; border-top: 1px solid var(--pi-border); }
614
616
  .queued-message:first-of-type { padding-top: 0; border-top: 0; }
617
+ .queued-message-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 22px; }
618
+ .queued-copy-button { flex: 0 0 auto; display: inline-grid; place-items: center; width: 22px; height: 22px; padding: 0; border: 1px solid var(--pi-border); border-radius: 4px; background: transparent; color: var(--pi-text-dim); cursor: pointer; }
619
+ .queued-copy-button:hover, .queued-copy-button:focus-visible { color: var(--pi-accent); border-color: var(--pi-accent); background: var(--pi-surface-hover); }
620
+ .queued-copy-button:focus-visible { outline: 1px solid var(--pi-border); outline-offset: 2px; }
615
621
  .queued-kind { color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
616
622
  .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; }
617
623
  .session-activity.compacting { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
@@ -1097,7 +1103,7 @@ This will delete every archived session on this machine regardless of age or cle
1097
1103
  .review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1098
1104
  .dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; overflow-wrap: anywhere; }
1099
1105
  footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
1100
- `]}};B([x({attribute:!1})],Cm.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],Cm.prototype,`uploadInput`,void 0),B([S()],Cm.prototype,`pendingUpload`,void 0),B([S()],Cm.prototype,`destinationFolder`,void 0),B([S()],Cm.prototype,`overwrite`,void 0),B([S()],Cm.prototype,`createDirs`,void 0),B([S()],Cm.prototype,`formError`,void 0),B([S()],Cm.prototype,`dragActive`,void 0),Cm=B([b(`workspace-files-panel`)],Cm);function wm(e,t){return Object.values(e).filter(e=>e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.machineId===t.machineId).sort((e,t)=>t.startedAt.localeCompare(e.startedAt))}function Tm(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Eo(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Em(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Dm(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${Bm(t.size)}`}function Om(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function km(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Am(e){return e==null?[]:Array.from(e)}function jm(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Mm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function Nm(e){let t=e.files.length,n=t===1?`file`:`files`;switch(e.status){case`completed`:return`Uploaded ${String(t)} ${n}`;case`error`:return`Upload failed for ${String(t)} ${n}`;case`cancelled`:return`Upload cancelled for ${String(t)} ${n}`;case`uploading`:return`Uploading ${String(t)} ${n}`}}function Pm(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return Rm(e.percent)}}function Fm(e){return e.status===`uploading`?e.percent:1}function Im(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return Rm(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Lm(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Bm(e.loaded)} / ${Bm(e.total)}`:`Wrote ${e.response.path}`:e.error}function Rm(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function zm(){Sm(()=>import(`./CodeViewer-BJJZQ999.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function Bm(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${Vm(t)} KB`;let n=t/1024;return n<1024?`${Vm(n)} MB`:`${Vm(n/1024)} GB`}function Vm(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var Hm=2e3,Um=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.dynamicMetricsRequest=0,this.dynamicMetricsRefreshInFlight=!1}willUpdate(e){if(!e.has(`context`))return;let t=this.context?.machine.id;if(t===void 0){this.stopDynamicMetricsPolling(),this.machineId=void 0;return}t!==this.machineId&&(this.stopDynamicMetricsPolling(),this.machineId=t,this.loadSystemInfo(t))}async loadSystemInfo(e=this.machineId){if(e!==void 0){this.loading=!0,this.error=``;try{let t=await Va.systemInfo(e);this.isCurrentMachine(e)&&(this.systemInfo=t,this.isConnected&&this.startDynamicMetricsPolling())}catch(t){this.isCurrentMachine(e)&&(this.error=t instanceof Error?t.message:String(t))}finally{this.isCurrentMachine(e)&&(this.loading=!1)}}}connectedCallback(){super.connectedCallback(),this.startDynamicMetricsPolling()}disconnectedCallback(){this.stopDynamicMetricsPolling(),super.disconnectedCallback()}startDynamicMetricsPolling(){let e=this.machineId;e===void 0||this.systemInfo===void 0||this.dynamicMetricsTimer!==void 0||(this.dynamicMetricsPollingMachineId=e,this.dynamicMetricsTimer=window.setInterval(()=>{this.refreshDynamicMetrics(e)},Hm))}stopDynamicMetricsPolling(){this.dynamicMetricsTimer!==void 0&&window.clearInterval(this.dynamicMetricsTimer),this.dynamicMetricsTimer=void 0,this.dynamicMetricsPollingMachineId=void 0,this.dynamicMetricsRequest+=1,this.dynamicMetricsRefreshInFlight=!1}async refreshDynamicMetrics(e){if(this.loading||this.error!==``||this.dynamicMetricsRefreshInFlight||this.dynamicMetricsPollingMachineId!==e)return;this.dynamicMetricsRefreshInFlight=!0;let t=++this.dynamicMetricsRequest;try{let n=await Va.systemMetrics(e);if(!this.isCurrentDynamicMetricsRequest(e,t))return;this.applyDynamicMetrics(n)}catch{}finally{t===this.dynamicMetricsRequest&&(this.dynamicMetricsRefreshInFlight=!1)}}isCurrentDynamicMetricsRequest(e,t){return t===this.dynamicMetricsRequest&&this.dynamicMetricsPollingMachineId===e&&this.isCurrentMachine(e)}applyDynamicMetrics(e){let t=this.systemInfo;t!==void 0&&(this.systemInfo={...t,memory:e.memory,network:{...t.network,...e.network}})}isCurrentMachine(e){return this.machineId===e&&this.context?.machine.id===e}render(){if(this.loading)return g`<section class="info-panel"><p class="muted">Loading system information…</p></section>`;if(this.error!==``)return g`<section class="info-panel">
1106
+ `]}};B([x({attribute:!1})],Cm.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],Cm.prototype,`uploadInput`,void 0),B([S()],Cm.prototype,`pendingUpload`,void 0),B([S()],Cm.prototype,`destinationFolder`,void 0),B([S()],Cm.prototype,`overwrite`,void 0),B([S()],Cm.prototype,`createDirs`,void 0),B([S()],Cm.prototype,`formError`,void 0),B([S()],Cm.prototype,`dragActive`,void 0),Cm=B([b(`workspace-files-panel`)],Cm);function wm(e,t){return Object.values(e).filter(e=>e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.machineId===t.machineId).sort((e,t)=>t.startedAt.localeCompare(e.startedAt))}function Tm(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Eo(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Em(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Dm(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${Bm(t.size)}`}function Om(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function km(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Am(e){return e==null?[]:Array.from(e)}function jm(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Mm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function Nm(e){let t=e.files.length,n=t===1?`file`:`files`;switch(e.status){case`completed`:return`Uploaded ${String(t)} ${n}`;case`error`:return`Upload failed for ${String(t)} ${n}`;case`cancelled`:return`Upload cancelled for ${String(t)} ${n}`;case`uploading`:return`Uploading ${String(t)} ${n}`}}function Pm(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return Rm(e.percent)}}function Fm(e){return e.status===`uploading`?e.percent:1}function Im(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return Rm(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Lm(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Bm(e.loaded)} / ${Bm(e.total)}`:`Wrote ${e.response.path}`:e.error}function Rm(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function zm(){Sm(()=>import(`./CodeViewer-BIb2Wx8W.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function Bm(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${Vm(t)} KB`;let n=t/1024;return n<1024?`${Vm(n)} MB`:`${Vm(n/1024)} GB`}function Vm(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var Hm=2e3,Um=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.dynamicMetricsRequest=0,this.dynamicMetricsRefreshInFlight=!1}willUpdate(e){if(!e.has(`context`))return;let t=this.context?.machine.id;if(t===void 0){this.stopDynamicMetricsPolling(),this.machineId=void 0;return}t!==this.machineId&&(this.stopDynamicMetricsPolling(),this.machineId=t,this.loadSystemInfo(t))}async loadSystemInfo(e=this.machineId){if(e!==void 0){this.loading=!0,this.error=``;try{let t=await Va.systemInfo(e);this.isCurrentMachine(e)&&(this.systemInfo=t,this.isConnected&&this.startDynamicMetricsPolling())}catch(t){this.isCurrentMachine(e)&&(this.error=t instanceof Error?t.message:String(t))}finally{this.isCurrentMachine(e)&&(this.loading=!1)}}}connectedCallback(){super.connectedCallback(),this.startDynamicMetricsPolling()}disconnectedCallback(){this.stopDynamicMetricsPolling(),super.disconnectedCallback()}startDynamicMetricsPolling(){let e=this.machineId;e===void 0||this.systemInfo===void 0||this.dynamicMetricsTimer!==void 0||(this.dynamicMetricsPollingMachineId=e,this.dynamicMetricsTimer=window.setInterval(()=>{this.refreshDynamicMetrics(e)},Hm))}stopDynamicMetricsPolling(){this.dynamicMetricsTimer!==void 0&&window.clearInterval(this.dynamicMetricsTimer),this.dynamicMetricsTimer=void 0,this.dynamicMetricsPollingMachineId=void 0,this.dynamicMetricsRequest+=1,this.dynamicMetricsRefreshInFlight=!1}async refreshDynamicMetrics(e){if(this.loading||this.error!==``||this.dynamicMetricsRefreshInFlight||this.dynamicMetricsPollingMachineId!==e)return;this.dynamicMetricsRefreshInFlight=!0;let t=++this.dynamicMetricsRequest;try{let n=await Va.systemMetrics(e);if(!this.isCurrentDynamicMetricsRequest(e,t))return;this.applyDynamicMetrics(n)}catch{}finally{t===this.dynamicMetricsRequest&&(this.dynamicMetricsRefreshInFlight=!1)}}isCurrentDynamicMetricsRequest(e,t){return t===this.dynamicMetricsRequest&&this.dynamicMetricsPollingMachineId===e&&this.isCurrentMachine(e)}applyDynamicMetrics(e){let t=this.systemInfo;t!==void 0&&(this.systemInfo={...t,memory:e.memory,network:{...t.network,...e.network}})}isCurrentMachine(e){return this.machineId===e&&this.context?.machine.id===e}render(){if(this.loading)return g`<section class="info-panel"><p class="muted">Loading system information…</p></section>`;if(this.error!==``)return g`<section class="info-panel">
1101
1107
  <p class="error-text">Failed to load system information: ${this.error}</p>
1102
1108
  <button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
1103
1109
  </section>`;let e=this.systemInfo;return e===void 0?g`<section class="info-panel"><p class="muted">System information unavailable.</p></section>`:g`<section class="info-panel">
@@ -1351,7 +1357,7 @@ This will delete every archived session on this machine regardless of age or cle
1351
1357
  <div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
1352
1358
  <unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
1353
1359
  </section>
1354
- `}function nh(){Sm(()=>import(`./UnifiedDiffViewer-jpQy9-p7.js`),[],import.meta.url)}function rh(){Sm(()=>Promise.resolve().then(()=>AO),void 0,import.meta.url)}function ih(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function ah(e){let t=oh(e);return g`
1360
+ `}function nh(){Sm(()=>import(`./UnifiedDiffViewer-DpWiGlQo.js`),[],import.meta.url)}function rh(){Sm(()=>Promise.resolve().then(()=>jO),void 0,import.meta.url)}function ih(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function ah(e){let t=oh(e);return g`
1355
1361
  <p class="summary">
1356
1362
  <span class="summary-branch">${t.branch}</span>
1357
1363
  ${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
@@ -1915,7 +1921,7 @@ This will delete every archived session on this machine regardless of age or cle
1915
1921
  </div>
1916
1922
  `}
1917
1923
  </dl>
1918
- `}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=v_(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}k_(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`})}static{this.styles=fm}};B([x({attribute:!1})],Hv.prototype,`workspaces`,void 0),B([x({attribute:!1})],Hv.prototype,`selected`,void 0),B([x({type:Boolean,reflect:!0})],Hv.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],Hv.prototype,`collapsed`,void 0),B([x({attribute:!1})],Hv.prototype,`workspaceLabelItems`,void 0),B([x({attribute:!1})],Hv.prototype,`activities`,void 0),B([x({attribute:!1})],Hv.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],Hv.prototype,`onSelect`,void 0),B([x({attribute:!1})],Hv.prototype,`onDelete`,void 0),B([x({attribute:!1})],Hv.prototype,`onToggleCollapsed`,void 0),B([x({attribute:!1})],Hv.prototype,`onFocusPreviousSection`,void 0),B([x({attribute:!1})],Hv.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],Hv.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],Hv.prototype,`openMenuWorkspaceId`,void 0),B([S()],Hv.prototype,`menuStyle`,void 0),Hv=B([b(`workspace-list`)],Hv);function Uv(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function Wv(e){return e.isGitWorktree&&!e.isMain}function Gv(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}var U=class extends y{constructor(...e){super(...e),this.canCleanup=!0,this.unavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.loading=!1,this.running=!1,this.error=``,this.runningForce=!1,this.draft={...Xf},this.formError=``}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd))}render(){let e=Zf(this.draft),t=this.selectedPreview(),n=$f({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),r=n?`Run cleanup`:t!==void 0&&!ep(t)?`Select at least one project to run cleanup`:`Preview cleanup before running it`;return g`
1924
+ `}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=v_(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}k_(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`})}static{this.styles=fm}};B([x({attribute:!1})],Hv.prototype,`workspaces`,void 0),B([x({attribute:!1})],Hv.prototype,`selected`,void 0),B([x({type:Boolean,reflect:!0})],Hv.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],Hv.prototype,`collapsed`,void 0),B([x({attribute:!1})],Hv.prototype,`workspaceLabelItems`,void 0),B([x({attribute:!1})],Hv.prototype,`activities`,void 0),B([x({attribute:!1})],Hv.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],Hv.prototype,`onSelect`,void 0),B([x({attribute:!1})],Hv.prototype,`onDelete`,void 0),B([x({attribute:!1})],Hv.prototype,`onToggleCollapsed`,void 0),B([x({attribute:!1})],Hv.prototype,`onFocusPreviousSection`,void 0),B([x({attribute:!1})],Hv.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],Hv.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],Hv.prototype,`openMenuWorkspaceId`,void 0),B([S()],Hv.prototype,`menuStyle`,void 0),Hv=B([b(`workspace-list`)],Hv);function Uv(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function Wv(e){return e.isGitWorktree&&!e.isMain}function Gv(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}var Kv=class extends y{constructor(...e){super(...e),this.canCleanup=!0,this.unavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.loading=!1,this.running=!1,this.error=``,this.runningForce=!1,this.draft={...Xf},this.formError=``}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd))}render(){let e=Zf(this.draft),t=this.selectedPreview(),n=$f({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),r=n?`Run cleanup`:t!==void 0&&!ep(t)?`Select at least one project to run cleanup`:`Preview cleanup before running it`;return g`
1919
1925
  <div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
1920
1926
  <section role="dialog" aria-modal="true" aria-label="Clean up sessions" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1921
1927
  <header>
@@ -1944,15 +1950,15 @@ This will delete every archived session on this machine regardless of age or cle
1944
1950
  `}renderForm(e){let t=this.loading||this.running,n=Zf(this.draft),r=this.preview!==void 0&&n.ok&&Qf(n.request)!==Qf(this.previewRequest)&&ep(this.preview);return g`
1945
1951
  <fieldset ?disabled=${t}>
1946
1952
  <label class="toggle-row">
1947
- <input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:Kv(e)})}}>
1953
+ <input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:qv(e)})}}>
1948
1954
  <span>Archive non-archived sessions idle for more than</span>
1949
- <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${e=>{this.updateDraft({archiveIdleDays:qv(e)})}}>
1955
+ <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${e=>{this.updateDraft({archiveIdleDays:Jv(e)})}}>
1950
1956
  <span>days</span>
1951
1957
  </label>
1952
1958
  <label class="toggle-row delete-row">
1953
- <input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:Kv(e)})}}>
1959
+ <input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:qv(e)})}}>
1954
1960
  <span>Delete archived sessions archived for more than</span>
1955
- <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${e=>{this.updateDraft({deleteArchivedDays:qv(e)})}}>
1961
+ <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${e=>{this.updateDraft({deleteArchivedDays:Jv(e)})}}>
1956
1962
  <span>days</span>
1957
1963
  </label>
1958
1964
  </fieldset>
@@ -1989,7 +1995,7 @@ This will delete every archived session on this machine regardless of age or cle
1989
1995
  ${t.length===0?g`<p class="hint" role="status">Select at least one project to run cleanup.</p>`:null}
1990
1996
  `}renderProjectRow(e,t){return g`
1991
1997
  <tr class=${t?``:`unselected`}>
1992
- <td class="select-cell"><input type="checkbox" aria-label=${`Clean up ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,Kv(t))}}></td>
1998
+ <td class="select-cell"><input type="checkbox" aria-label=${`Clean up ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,qv(t))}}></td>
1993
1999
  <th title=${e.cwd} dir="auto">${e.cwd}</th>
1994
2000
  <td>${e.archiveCount}</td>
1995
2001
  <td>${e.deleteCount}</td>
@@ -2056,7 +2062,7 @@ This will delete every archived session on this machine regardless of age or cle
2056
2062
  table { min-width: 560px; }
2057
2063
  thead th:first-child, td.select-cell { width: 58px; }
2058
2064
  }
2059
- `}};B([x({type:Boolean})],U.prototype,`canCleanup`,void 0),B([x({type:String})],U.prototype,`unavailableMessage`,void 0),B([x({attribute:!1})],U.prototype,`preview`,void 0),B([x({attribute:!1})],U.prototype,`previewRequest`,void 0),B([x({attribute:!1})],U.prototype,`result`,void 0),B([x({type:Boolean})],U.prototype,`loading`,void 0),B([x({type:Boolean})],U.prototype,`running`,void 0),B([x({type:String})],U.prototype,`error`,void 0),B([x({attribute:!1})],U.prototype,`onPreview`,void 0),B([x({attribute:!1})],U.prototype,`onRun`,void 0),B([x({attribute:!1})],U.prototype,`onForceCleanup`,void 0),B([x({attribute:!1})],U.prototype,`onClose`,void 0),B([x({attribute:!1})],U.prototype,`forceCleanupResult`,void 0),B([x({type:Boolean})],U.prototype,`runningForce`,void 0),B([S()],U.prototype,`draft`,void 0),B([S()],U.prototype,`formError`,void 0),B([S()],U.prototype,`selectedProjectCwds`,void 0),U=B([b(`session-cleanup-dialog`)],U);function Kv(e){return e.target instanceof HTMLInputElement&&e.target.checked}function qv(e){return e.target instanceof HTMLInputElement?e.target.value:``}var Jv=class extends y{constructor(...e){super(...e),this.machineId=`local`}render(){let e=this.session,t=e===void 0?void 0:bt(ka(e,this.machineId)),n=e===void 0?``:Yv(e);return g`
2065
+ `}};B([x({type:Boolean})],Kv.prototype,`canCleanup`,void 0),B([x({type:String})],Kv.prototype,`unavailableMessage`,void 0),B([x({attribute:!1})],Kv.prototype,`preview`,void 0),B([x({attribute:!1})],Kv.prototype,`previewRequest`,void 0),B([x({attribute:!1})],Kv.prototype,`result`,void 0),B([x({type:Boolean})],Kv.prototype,`loading`,void 0),B([x({type:Boolean})],Kv.prototype,`running`,void 0),B([x({type:String})],Kv.prototype,`error`,void 0),B([x({attribute:!1})],Kv.prototype,`onPreview`,void 0),B([x({attribute:!1})],Kv.prototype,`onRun`,void 0),B([x({attribute:!1})],Kv.prototype,`onForceCleanup`,void 0),B([x({attribute:!1})],Kv.prototype,`onClose`,void 0),B([x({attribute:!1})],Kv.prototype,`forceCleanupResult`,void 0),B([x({type:Boolean})],Kv.prototype,`runningForce`,void 0),B([S()],Kv.prototype,`draft`,void 0),B([S()],Kv.prototype,`formError`,void 0),B([S()],Kv.prototype,`selectedProjectCwds`,void 0),Kv=B([b(`session-cleanup-dialog`)],Kv);function qv(e){return e.target instanceof HTMLInputElement&&e.target.checked}function Jv(e){return e.target instanceof HTMLInputElement?e.target.value:``}var Yv=class extends y{constructor(...e){super(...e),this.machineId=`local`}render(){let e=this.session,t=e===void 0?void 0:bt(ka(e,this.machineId)),n=e===void 0?``:Xv(e);return g`
2060
2066
  <div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
2061
2067
  <section class="history-window" role="dialog" aria-modal="true" aria-labelledby="session-history-window-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
2062
2068
  <header>
@@ -2066,7 +2072,7 @@ This will delete every archived session on this machine regardless of age or cle
2066
2072
  ${e===void 0?null:g`<span class="session-label" title=${n}>${n}</span>`}
2067
2073
  </div>
2068
2074
  <button class="icon-button" type="button" title="Close full history" aria-label="Close full history" @click=${()=>{this.close()}}>
2069
- ${Xv()}
2075
+ ${Zv()}
2070
2076
  </button>
2071
2077
  </header>
2072
2078
  <div class="history-body">
@@ -2103,11 +2109,11 @@ This will delete every archived session on this machine regardless of age or cle
2103
2109
  header, footer { padding: 12px; }
2104
2110
  .session-label { max-width: 68vw; }
2105
2111
  }
2106
- `}};B([x({attribute:!1})],Jv.prototype,`session`,void 0),B([x({type:String})],Jv.prototype,`machineId`,void 0),B([x({attribute:!1})],Jv.prototype,`onClose`,void 0),Jv=B([b(`session-history-window`)],Jv);function Yv(e){let t=e.name?.trim();if(t!==void 0&&t!==``)return t;let n=e.firstMessage.trim();return n===``?e.id:n}function Xv(){return _`
2112
+ `}};B([x({attribute:!1})],Yv.prototype,`session`,void 0),B([x({type:String})],Yv.prototype,`machineId`,void 0),B([x({attribute:!1})],Yv.prototype,`onClose`,void 0),Yv=B([b(`session-history-window`)],Yv);function Xv(e){let t=e.name?.trim();if(t!==void 0&&t!==``)return t;let n=e.firstMessage.trim();return n===``?e.id:n}function Zv(){return _`
2107
2113
  <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2108
2114
  <path d="M6 6l12 12M18 6 6 18"></path>
2109
2115
  </svg>
2110
- `}function Zv(e){let t=new Map,n=[];for(let r of e.nodes)t.has(r.id)||(t.set(r.id,r),n.push(r.id));let r=ry(t,n),i=new Map;for(let e of n)i.set(e,[]);let a=[];for(let e of n){let t=r.get(e)??null;if(t===null){a.push(e);continue}i.get(t)?.push(e)}let o=new Map,s=new Map,c=new Set,l=[...a].reverse().map(e=>({id:e,depth:0,branchDepth:0}));for(;l.length>0;){let e=l.pop();if(e===void 0||c.has(e.id))continue;c.add(e.id),o.set(e.id,e.depth),s.set(e.id,e.branchDepth);let t=i.get(e.id)??[],n=e.branchDepth+ +(t.length>1);for(let r=t.length-1;r>=0;--r){let i=t[r];i!==void 0&&l.push({id:i,depth:e.depth+1,branchDepth:n})}}for(let e of n)c.has(e)||(a.push(e),r.set(e,null),o.set(e,0),s.set(e,0));let u=new Map;for(let[e,t]of i)u.set(e,t);let d=e.activeLeafId!==null&&t.has(e.activeLeafId)?e.activeLeafId:null;return{nodesById:t,orderedIds:n,rootIds:a,parentById:r,childrenById:u,depthById:o,branchDepthById:s,activePathIds:d===null?new Set:iy(d,r),activeLeafId:d}}function Qv(e,t){let n=[],r=new Set,i=[...e.rootIds].reverse();for(;i.length>0;){let a=i.pop();if(a===void 0||r.has(a))continue;let o=e.nodesById.get(a);if(o===void 0)continue;r.add(a);let s=e.childrenById.get(a)??[];if(n.push({node:o,depth:e.depthById.get(a)??0,branchDepth:e.branchDepthById.get(a)??0,parentId:e.parentById.get(a)??null,childIds:s,activePath:e.activePathIds.has(a),activeLeaf:e.activeLeafId===a}),!t.has(a))for(let e=s.length-1;e>=0;--e){let t=s[e];t!==void 0&&i.push(t)}}return n}function $v(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function ey(e,t,n){let r=Qv(e,t.foldedIds).map(e=>e.node.id),i=ay(r,t.selectedId),a=i===void 0?-1:r.indexOf(i),o=()=>({...t,selectedId:i,handled:!1}),s=e=>({...t,selectedId:e,handled:!0});switch(n){case`ArrowUp`:return s(a>0?r[a-1]:i);case`ArrowDown`:return s(a>=0&&a<r.length-1?r[a+1]:i);case`Home`:return s(r[0]);case`End`:return s(r.at(-1));case`ArrowLeft`:if(i===void 0)return s(void 0);if((e.childrenById.get(i)??[]).length>0&&!t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.add(i),{selectedId:i,foldedIds:e,handled:!0}}return s(e.parentById.get(i)??i);case`ArrowRight`:{if(i===void 0)return s(void 0);let n=e.childrenById.get(i)??[];if(n.length===0)return s(i);if(t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.delete(i),{selectedId:i,foldedIds:e,handled:!0}}return s(n[0])}case`Enter`:return{...t,selectedId:i,handled:!0,...i===void 0?{}:{action:`confirm`}};case`Escape`:return{...t,selectedId:i,handled:!0,action:`cancel`};default:return o()}}function ty(e,t,n){if((e.childrenById.get(n)??[]).length===0)return{...t,selectedId:n};let r=new Set(t.foldedIds);return r.has(n)?r.delete(n):r.add(n),{selectedId:n,foldedIds:r}}function ny(e,t){return e===`none`||e==="default"?{ok:!0,choice:{mode:e}}:t.trim()===``?{ok:!1,error:`Enter custom summary focus instructions.`}:t.length>1e4?{ok:!1,error:`Custom summary focus must be ${String(kt)} characters or fewer.`}:{ok:!0,choice:{mode:`custom`,instructions:t.trim()}}}function ry(e,t){let n=new Map;for(let r of t){let t=e.get(r)?.parentId??null;n.set(r,t!==null&&t!==r&&e.has(t)?t:null)}let r=new Map;for(let e of t){if(r.has(e))continue;let t=[],i=e;for(;i!==null&&!r.has(i);)r.set(i,`visiting`),t.push(i),i=n.get(i)??null;if(i!==null&&r.get(i)===`visiting`){let e=t.at(-1);e!==void 0&&n.set(e,null)}for(let e of t)r.set(e,`visited`)}return n}function iy(e,t){let n=new Set,r=e;for(;r!==null&&!n.has(r);)n.add(r),r=t.get(r)??null;return n}function ay(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var oy={nodes:[],activeLeafId:null,activePathIds:[]},sy=8,cy=class extends y{constructor(...e){super(...e),this.tree=oy,this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.model=Zv(oy),this.operationGeneration=0}willUpdate(e){e.has(`tree`)&&this.resetTree()}updated(){let e=this.pendingFocus;e!==void 0&&(this.pendingFocus=void 0,e===`tree`?this.focusSelectedTreeItem():e===`custom`?this.renderRoot.querySelector(`#session-tree-custom-focus`)?.focus():this.renderRoot.querySelector(`input[name='session-tree-summary']:checked`)?.focus())}render(){return g`
2116
+ `}function Qv(e){let t=new Map,n=[];for(let r of e.nodes)t.has(r.id)||(t.set(r.id,r),n.push(r.id));let r=iy(t,n),i=new Map;for(let e of n)i.set(e,[]);let a=[];for(let e of n){let t=r.get(e)??null;if(t===null){a.push(e);continue}i.get(t)?.push(e)}let o=new Map,s=new Map,c=new Set,l=[...a].reverse().map(e=>({id:e,depth:0,branchDepth:0}));for(;l.length>0;){let e=l.pop();if(e===void 0||c.has(e.id))continue;c.add(e.id),o.set(e.id,e.depth),s.set(e.id,e.branchDepth);let t=i.get(e.id)??[],n=e.branchDepth+ +(t.length>1);for(let r=t.length-1;r>=0;--r){let i=t[r];i!==void 0&&l.push({id:i,depth:e.depth+1,branchDepth:n})}}for(let e of n)c.has(e)||(a.push(e),r.set(e,null),o.set(e,0),s.set(e,0));let u=new Map;for(let[e,t]of i)u.set(e,t);let d=e.activeLeafId!==null&&t.has(e.activeLeafId)?e.activeLeafId:null;return{nodesById:t,orderedIds:n,rootIds:a,parentById:r,childrenById:u,depthById:o,branchDepthById:s,activePathIds:d===null?new Set:ay(d,r),activeLeafId:d}}function $v(e,t){let n=[],r=new Set,i=[...e.rootIds].reverse();for(;i.length>0;){let a=i.pop();if(a===void 0||r.has(a))continue;let o=e.nodesById.get(a);if(o===void 0)continue;r.add(a);let s=e.childrenById.get(a)??[];if(n.push({node:o,depth:e.depthById.get(a)??0,branchDepth:e.branchDepthById.get(a)??0,parentId:e.parentById.get(a)??null,childIds:s,activePath:e.activePathIds.has(a),activeLeaf:e.activeLeafId===a}),!t.has(a))for(let e=s.length-1;e>=0;--e){let t=s[e];t!==void 0&&i.push(t)}}return n}function ey(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function ty(e,t,n){let r=$v(e,t.foldedIds).map(e=>e.node.id),i=oy(r,t.selectedId),a=i===void 0?-1:r.indexOf(i),o=()=>({...t,selectedId:i,handled:!1}),s=e=>({...t,selectedId:e,handled:!0});switch(n){case`ArrowUp`:return s(a>0?r[a-1]:i);case`ArrowDown`:return s(a>=0&&a<r.length-1?r[a+1]:i);case`Home`:return s(r[0]);case`End`:return s(r.at(-1));case`ArrowLeft`:if(i===void 0)return s(void 0);if((e.childrenById.get(i)??[]).length>0&&!t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.add(i),{selectedId:i,foldedIds:e,handled:!0}}return s(e.parentById.get(i)??i);case`ArrowRight`:{if(i===void 0)return s(void 0);let n=e.childrenById.get(i)??[];if(n.length===0)return s(i);if(t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.delete(i),{selectedId:i,foldedIds:e,handled:!0}}return s(n[0])}case`Enter`:return{...t,selectedId:i,handled:!0,...i===void 0?{}:{action:`confirm`}};case`Escape`:return{...t,selectedId:i,handled:!0,action:`cancel`};default:return o()}}function ny(e,t,n){if((e.childrenById.get(n)??[]).length===0)return{...t,selectedId:n};let r=new Set(t.foldedIds);return r.has(n)?r.delete(n):r.add(n),{selectedId:n,foldedIds:r}}function ry(e,t){return e===`none`||e==="default"?{ok:!0,choice:{mode:e}}:t.trim()===``?{ok:!1,error:`Enter custom summary focus instructions.`}:t.length>1e4?{ok:!1,error:`Custom summary focus must be ${String(kt)} characters or fewer.`}:{ok:!0,choice:{mode:`custom`,instructions:t.trim()}}}function iy(e,t){let n=new Map;for(let r of t){let t=e.get(r)?.parentId??null;n.set(r,t!==null&&t!==r&&e.has(t)?t:null)}let r=new Map;for(let e of t){if(r.has(e))continue;let t=[],i=e;for(;i!==null&&!r.has(i);)r.set(i,`visiting`),t.push(i),i=n.get(i)??null;if(i!==null&&r.get(i)===`visiting`){let e=t.at(-1);e!==void 0&&n.set(e,null)}for(let e of t)r.set(e,`visited`)}return n}function ay(e,t){let n=new Set,r=e;for(;r!==null&&!n.has(r);)n.add(r),r=t.get(r)??null;return n}function oy(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var sy={nodes:[],activeLeafId:null,activePathIds:[]},cy=8,ly=class extends y{constructor(...e){super(...e),this.tree=sy,this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.model=Qv(sy),this.operationGeneration=0}willUpdate(e){e.has(`tree`)&&this.resetTree()}updated(){let e=this.pendingFocus;e!==void 0&&(this.pendingFocus=void 0,e===`tree`?this.focusSelectedTreeItem():e===`custom`?this.renderRoot.querySelector(`#session-tree-custom-focus`)?.focus():this.renderRoot.querySelector(`input[name='session-tree-summary']:checked`)?.focus())}render(){return g`
2111
2117
  <div class="backdrop" @mousedown=${e=>{this.handleBackdropMouseDown(e)}}>
2112
2118
  <section
2113
2119
  role="dialog"
@@ -2129,7 +2135,7 @@ This will delete every archived session on this machine regardless of age or cle
2129
2135
  ${this.renderFooter()}
2130
2136
  </section>
2131
2137
  </div>
2132
- `}renderTreeStep(){let e=Qv(this.model,this.foldedIds);return g`
2138
+ `}renderTreeStep(){let e=$v(this.model,this.foldedIds);return g`
2133
2139
  <div class="body tree-step">
2134
2140
  <div class="tree-intro">
2135
2141
  <p>Select where conversation context should continue. All retained branches stay in this session file.</p>
@@ -2148,7 +2154,7 @@ This will delete every archived session on this machine regardless of age or cle
2148
2154
  </div>
2149
2155
  `}
2150
2156
  </div>
2151
- `}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,fy(e.node.kind)?`bookkeeping`:``].filter(e=>e!==``).join(` `),i=ly(e.branchDepth);return g`
2157
+ `}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,py(e.node.kind)?`bookkeeping`:``].filter(e=>e!==``).join(` `),i=uy(e.branchDepth);return g`
2152
2158
  <div
2153
2159
  class=${r}
2154
2160
  style=${`--tree-indent: ${String(i*16)}px; --tree-indent-mobile: ${String(i*12)}px;`}
@@ -2169,7 +2175,7 @@ This will delete every archived session on this machine regardless of age or cle
2169
2175
  @click=${t=>{this.toggleNode(e.node.id,t)}}
2170
2176
  >${e.childIds.length===0?`·`:n?`▾`:`▸`}</span>
2171
2177
  <span class="metadata">
2172
- <span class="kind">${dy(e.node.kind)}</span>
2178
+ <span class="kind">${fy(e.node.kind)}</span>
2173
2179
  <span class="badges">
2174
2180
  ${e.activePath&&!e.activeLeaf?g`<span class="badge path">Active path</span>`:null}
2175
2181
  ${e.activeLeaf?g`<span class="badge leaf">Active leaf</span>`:null}
@@ -2181,7 +2187,7 @@ This will delete every archived session on this machine regardless of age or cle
2181
2187
  ${e.node.timestamp===void 0?null:g`<time datetime=${e.node.timestamp}>${e.node.timestamp}</time>`}
2182
2188
  </span>
2183
2189
  </div>
2184
- `}renderConfirmationStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=ny(this.summaryMode,this.customInstructions);return g`
2190
+ `}renderConfirmationStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=ry(this.summaryMode,this.customInstructions);return g`
2185
2191
  <div class="body confirmation-step">
2186
2192
  <div class="confirmation-card">
2187
2193
  <div>
@@ -2190,9 +2196,9 @@ This will delete every archived session on this machine regardless of age or cle
2190
2196
  </div>
2191
2197
  ${e===void 0?g`<div class="empty">The selected history entry is no longer available.</div>`:g`
2192
2198
  <div class="selected-entry">
2193
- <span class="kind">${dy(e.kind)}</span>
2199
+ <span class="kind">${fy(e.kind)}</span>
2194
2200
  <strong dir="auto">${e.summary}</strong>
2195
- ${uy(e.kind)?g`<p>This message’s text will return to the prompt editor for optional editing and resubmission.</p>`:g`<p>The prompt editor will be empty after navigating to this entry.</p>`}
2201
+ ${dy(e.kind)?g`<p>This message’s text will return to the prompt editor for optional editing and resubmission.</p>`:g`<p>The prompt editor will be empty after navigating to this entry.</p>`}
2196
2202
  </div>
2197
2203
  `}
2198
2204
  <fieldset ?disabled=${this.busy}>
@@ -2249,7 +2255,7 @@ This will delete every archived session on this machine regardless of age or cle
2249
2255
  ${this.busy?e?`Summarizing…`:`Navigating…`:e?`Summarize and navigate`:`Navigate`}
2250
2256
  </button>
2251
2257
  </footer>
2252
- `}resetTree(){this.operationGeneration+=1,this.model=Zv(this.tree),this.selectedId=$v(this.model),this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}selectNode(e){this.model.nodesById.has(e)&&(this.selectedId=e,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}toggleNode(e,t){t.preventDefault(),t.stopPropagation();let n=ty(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e);this.selectedId=n.selectedId,this.foldedIds=n.foldedIds,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}handleTreeKeyDown(e){let t=ey(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e.key);if(t.handled){if(e.preventDefault(),e.stopPropagation(),t.action===`cancel`){this.onCancel?.();return}if(t.action===`confirm`){this.continueToConfirmation();return}this.selectedId=t.selectedId,this.foldedIds=t.foldedIds,this.pendingFocus=`tree`}}continueToConfirmation(){this.selectedId===void 0||!this.model.nodesById.has(this.selectedId)||(ny(this.summaryMode,this.customInstructions).ok||(this.summaryMode=`none`,this.customInstructions=``),this.step=`confirm`,this.error=``,this.statusMessage=``,this.pendingFocus=`summary`)}returnToTree(){this.busy||(this.step=`tree`,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}selectSummaryMode(e){this.busy||(this.summaryMode=e,this.error=``,this.statusMessage=``,this.pendingFocus=e===`custom`?`custom`:`summary`)}handleCustomInstructionsInput(e){e.currentTarget instanceof HTMLTextAreaElement&&(this.customInstructions=e.currentTarget.value,this.error=``,this.statusMessage=``)}async submitNavigation(){if(this.busy||this.selectedId===void 0)return;let e=ny(this.summaryMode,this.customInstructions);if(!e.ok){this.error=``,this.statusMessage=``,this.pendingFocus=`custom`,this.requestUpdate();return}let t=this.onNavigate;if(t===void 0){this.error=`Session tree navigation is unavailable. Close and reopen /tree, then try again.`;return}let n=this.selectedId,r=++this.operationGeneration;this.busy=!0,this.aborting=!1,this.error=``,this.statusMessage=``;try{let i=await t(n,e.choice);if(r!==this.operationGeneration||(this.busy=!1,this.aborting=!1,!i.cancelled))return;this.step=`tree`,this.statusMessage=i.aborted===!0?`Summarization cancelled. Your selected history entry is unchanged.`:`Navigation cancelled. Your selected history entry is unchanged.`,this.pendingFocus=`tree`}catch(e){if(r!==this.operationGeneration)return;this.busy=!1,this.aborting=!1,this.statusMessage=``,this.error=`Could not navigate session history: ${py(e)}`}}async abortNavigation(){if(!this.busy||this.summaryMode===`none`||this.aborting)return;let e=this.onAbort;if(e===void 0){this.error=`Summarization cannot be cancelled from this client.`;return}let t=this.operationGeneration;this.aborting=!0,this.error=``,this.statusMessage=`Cancelling summarization…`;try{await e()}catch(e){if(t!==this.operationGeneration)return;this.aborting=!1,this.statusMessage=``,this.error=`Could not cancel summarization: ${py(e)}`}}handleBackdropMouseDown(e){e.target===e.currentTarget&&!this.busy&&this.onCancel?.()}handleDialogKeyDown(e){if(e.key===`Tab`){this.trapTabFocus(e);return}if(e.key===`Escape`){if(e.preventDefault(),e.stopPropagation(),this.busy){this.summaryMode!==`none`&&this.abortNavigation();return}this.step===`confirm`?this.returnToTree():this.onCancel?.()}}trapTabFocus(e){let t=[...this.renderRoot.querySelectorAll(`button:not(:disabled), input:not(:disabled), textarea:not(:disabled), [tabindex='0']`)];if(t.length===0){e.preventDefault(),this.renderRoot.querySelector(`section[role='dialog']`)?.focus();return}let n=this.shadowRoot?.activeElement,r=t.findIndex(e=>e===n),i=!e.shiftKey&&r===t.length-1,a=e.shiftKey&&r<=0;!i&&!a||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}focusSelectedTreeItem(){let e=this.selectedId;if(e===void 0){this.renderRoot.querySelector(`.close-button`)?.focus();return}let t=this.renderRoot.querySelectorAll(`[data-tree-node-id]`);for(let n of t)if(n.dataset.treeNodeId===e){n.focus(),n.scrollIntoView({block:`nearest`});return}}static{this.styles=h`
2258
+ `}resetTree(){this.operationGeneration+=1,this.model=Qv(this.tree),this.selectedId=ey(this.model),this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}selectNode(e){this.model.nodesById.has(e)&&(this.selectedId=e,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}toggleNode(e,t){t.preventDefault(),t.stopPropagation();let n=ny(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e);this.selectedId=n.selectedId,this.foldedIds=n.foldedIds,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}handleTreeKeyDown(e){let t=ty(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e.key);if(t.handled){if(e.preventDefault(),e.stopPropagation(),t.action===`cancel`){this.onCancel?.();return}if(t.action===`confirm`){this.continueToConfirmation();return}this.selectedId=t.selectedId,this.foldedIds=t.foldedIds,this.pendingFocus=`tree`}}continueToConfirmation(){this.selectedId===void 0||!this.model.nodesById.has(this.selectedId)||(ry(this.summaryMode,this.customInstructions).ok||(this.summaryMode=`none`,this.customInstructions=``),this.step=`confirm`,this.error=``,this.statusMessage=``,this.pendingFocus=`summary`)}returnToTree(){this.busy||(this.step=`tree`,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}selectSummaryMode(e){this.busy||(this.summaryMode=e,this.error=``,this.statusMessage=``,this.pendingFocus=e===`custom`?`custom`:`summary`)}handleCustomInstructionsInput(e){e.currentTarget instanceof HTMLTextAreaElement&&(this.customInstructions=e.currentTarget.value,this.error=``,this.statusMessage=``)}async submitNavigation(){if(this.busy||this.selectedId===void 0)return;let e=ry(this.summaryMode,this.customInstructions);if(!e.ok){this.error=``,this.statusMessage=``,this.pendingFocus=`custom`,this.requestUpdate();return}let t=this.onNavigate;if(t===void 0){this.error=`Session tree navigation is unavailable. Close and reopen /tree, then try again.`;return}let n=this.selectedId,r=++this.operationGeneration;this.busy=!0,this.aborting=!1,this.error=``,this.statusMessage=``;try{let i=await t(n,e.choice);if(r!==this.operationGeneration||(this.busy=!1,this.aborting=!1,!i.cancelled))return;this.step=`tree`,this.statusMessage=i.aborted===!0?`Summarization cancelled. Your selected history entry is unchanged.`:`Navigation cancelled. Your selected history entry is unchanged.`,this.pendingFocus=`tree`}catch(e){if(r!==this.operationGeneration)return;this.busy=!1,this.aborting=!1,this.statusMessage=``,this.error=`Could not navigate session history: ${my(e)}`}}async abortNavigation(){if(!this.busy||this.summaryMode===`none`||this.aborting)return;let e=this.onAbort;if(e===void 0){this.error=`Summarization cannot be cancelled from this client.`;return}let t=this.operationGeneration;this.aborting=!0,this.error=``,this.statusMessage=`Cancelling summarization…`;try{await e()}catch(e){if(t!==this.operationGeneration)return;this.aborting=!1,this.statusMessage=``,this.error=`Could not cancel summarization: ${my(e)}`}}handleBackdropMouseDown(e){e.target===e.currentTarget&&!this.busy&&this.onCancel?.()}handleDialogKeyDown(e){if(e.key===`Tab`){this.trapTabFocus(e);return}if(e.key===`Escape`){if(e.preventDefault(),e.stopPropagation(),this.busy){this.summaryMode!==`none`&&this.abortNavigation();return}this.step===`confirm`?this.returnToTree():this.onCancel?.()}}trapTabFocus(e){let t=[...this.renderRoot.querySelectorAll(`button:not(:disabled), input:not(:disabled), textarea:not(:disabled), [tabindex='0']`)];if(t.length===0){e.preventDefault(),this.renderRoot.querySelector(`section[role='dialog']`)?.focus();return}let n=this.shadowRoot?.activeElement,r=t.findIndex(e=>e===n),i=!e.shiftKey&&r===t.length-1,a=e.shiftKey&&r<=0;!i&&!a||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}focusSelectedTreeItem(){let e=this.selectedId;if(e===void 0){this.renderRoot.querySelector(`.close-button`)?.focus();return}let t=this.renderRoot.querySelectorAll(`[data-tree-node-id]`);for(let n of t)if(n.dataset.treeNodeId===e){n.focus(),n.scrollIntoView({block:`nearest`});return}}static{this.styles=h`
2253
2259
  :host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
2254
2260
  * { box-sizing: border-box; }
2255
2261
  .backdrop { width: 100%; height: 100dvh; background: var(--pi-overlay); overflow: hidden; }
@@ -2342,7 +2348,7 @@ This will delete every archived session on this machine regardless of age or cle
2342
2348
  .custom-focus, .validation-error { margin-inline-start: 0; }
2343
2349
  footer { flex-wrap: wrap; }
2344
2350
  }
2345
- `}};B([x({attribute:!1})],cy.prototype,`tree`,void 0),B([x({attribute:!1})],cy.prototype,`onNavigate`,void 0),B([x({attribute:!1})],cy.prototype,`onAbort`,void 0),B([x({attribute:!1})],cy.prototype,`onCancel`,void 0),B([S()],cy.prototype,`selectedId`,void 0),B([S()],cy.prototype,`foldedIds`,void 0),B([S()],cy.prototype,`step`,void 0),B([S()],cy.prototype,`summaryMode`,void 0),B([S()],cy.prototype,`customInstructions`,void 0),B([S()],cy.prototype,`busy`,void 0),B([S()],cy.prototype,`aborting`,void 0),B([S()],cy.prototype,`error`,void 0),B([S()],cy.prototype,`statusMessage`,void 0),cy=B([b(`session-tree-navigator`)],cy);function ly(e){return Math.min(Math.max(0,e),sy)}function uy(e){return e===`user`||e===`custom-message`}function dy(e){switch(e){case`user`:return`User`;case`assistant`:return`Assistant`;case`tool-result`:return`Tool result`;case`bash`:return`Shell`;case`custom-message`:return`Custom message`;case`compaction`:return`Compaction`;case`branch-summary`:return`Branch summary`;case`model-change`:return`Model`;case`thinking-level-change`:return`Thinking`;case`session-info`:return`Session info`;case`label`:return`Label`;case`custom`:return`Custom`;case`other`:return`Other`}}function fy(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function py(e){return e instanceof Error?e.message:String(e)}var my=`pi-webui:chat-groups:`,hy={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(_y(e));return t===null||t===``?void 0:vy(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(_y(e),JSON.stringify(t))}catch{}}},gy=class{constructor(e=hy){this.storage=e,this.sessionId=``,this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(e){if(this.sessionId===e)return;this.sessionId=e;let t=e===``?void 0:this.storage.read(e);this.openGroupKeys=new Set(t?.open??[]),this.closedDefaultOpenGroupKeys=new Set(t?.closedDefaultOpen??[])}isOpen(e,t){return t?!this.closedDefaultOpenGroupKeys.has(e):this.openGroupKeys.has(e)}applyToggle(e,t,n){let r=this.isOpen(e,n),i=new Set(this.openGroupKeys),a=new Set(this.closedDefaultOpenGroupKeys);return n?(i.delete(e),t?a.delete(e):a.add(e)):(a.delete(e),t?i.add(e):i.delete(e)),(n?!a.has(e):i.has(e))===r&&by(i,this.openGroupKeys)&&by(a,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=i,this.closedDefaultOpenGroupKeys=a,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==``&&this.storage.write(this.sessionId,this.snapshot())}};function _y(e){return`${my}${e}`}function vy(e){if(Array.isArray(e))return{open:yy(e),closedDefaultOpen:[]};if(xy(e))return{open:Array.isArray(e.open)?yy(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?yy(e.closedDefaultOpen):[]}}function yy(e){return e.filter(e=>typeof e==`string`)}function by(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function xy(e){return typeof e==`object`&&!!e}function Sy(e,t=0){let n=[],r=[],i=0,a=(e,t)=>{r.length||(i=t),r.push(e)},o=()=>{r.length&&(n.push({kind:`group`,messages:r,startIndex:i,endIndex:i+r.length-1}),r=[])};return e.forEach((e,r)=>{let i=e.parts.filter(t=>Ey(e,t)),s=e.parts.filter(t=>!Ey(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}},u={...l,...e.entryId===void 0?{}:{entryId:e.entryId},...e.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:e.previousAssistantEntryId},...e.canFork===void 0?{}:{canFork:e.canFork}};if(s.length&&a({role:e.role,parts:s,...l},c),i.length){o();let t={role:i.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:i,...u};if(wy(t)){let e=Ty(s);n.push({kind:`tool-image`,message:t,index:c,...e===void 0?{}:{toolName:e}})}else n.push({kind:`message`,message:t,index:c})}}),o(),n}function Cy(e){if(e.every(e=>e.source===`compaction`))return`${String(e.length)} history compaction ${e.length===1?`summary`:`summaries`}`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} branch ${e.length===1?`summary`:`summaries`}`;let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n=Object.entries(t).map(([e,t])=>`${String(t)} ${e}`).join(` · `);return`${String(e.length)} ${e.length===1?`event`:`events`}${n===``?``:` · ${n}`}`}function wy(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function Ty(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function Ey(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}async function Dy(e,t=Oy()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function Oy(){let e=e=>jy(e),t=Ay();return t===void 0?{isSecureContext:ky(),fallbackWriteText:e}:{isSecureContext:ky(),writeText:t,fallbackWriteText:e}}function ky(){return typeof window<`u`&&window.isSecureContext}function Ay(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function jy(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:My(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),Ny(n,r),Py(t)}}function My(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function Ny(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function Py(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function Fy(e,t){let n=Ly(By(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function Iy(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Ry(r,t.markerOffset);return}e.scrollTop=zy(e.scrollHeight,t.distanceFromBottom)}function Ly(e){let t,n=-1/0,r,i=1/0;for(let a of e)a.offset<=0&&a.offset>=n?(t=a,n=a.offset):a.offset>0&&a.offset<i&&(r=a,i=a.offset);return t??r}function Ry(e,t){return e-t}function zy(e,t){return Math.max(0,e-t)}function By(e,t){let n=e.getBoundingClientRect().top;return t.flatMap(e=>{let t=e.dataset.markerId;return t===void 0?[]:[{id:t,offset:e.getBoundingClientRect().top-n}]})}var Vy=600,Hy=1;function Uy(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Wy(e)||Gy(e)}function Wy(e){return e.scrollTop<(e.topThreshold??Math.max(Vy,e.clientHeight))}function Gy(e){return e.scrollHeight<=e.clientHeight+Hy}var Ky=`pi-webui:chat-scroll:`,qy=180,Jy=48,Yy=2,Xy={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)}},Zy={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},Qy=class{constructor(e=Xy,t=Zy){this.storage=e,this.scheduler=t}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(e,t,n=qy){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=Yy){if(e===``||t===void 0||!tb(t))return`skipped`;try{if(rb(t,r))return this.storage.setItem($y(e),JSON.stringify({mode:`bottom`})),`saved`;let i=ab(t,n);if(i===void 0)return`skipped`;let a=ib(t,i);return this.storage.setItem($y(e),JSON.stringify(a)),`saved`}catch{return`skipped`}}restorePosition(e,t,n,r){let i=this.readPosition(e);return i===void 0?this.scrollToBottom(t):this.restoreExplicitPosition(i,t,n,r)}restoreExplicitPosition(e,t,n,r){if(e.mode===`bottom`)return this.scrollToBottom(t);if(t===void 0||!tb(t))return{status:`skipped`};let i=sb(n,e.anchorId);if(i===void 0)return r?.fallbackToBottom===!1?{status:`missing`,position:e}:this.scrollToBottom(t);let a=t.getBoundingClientRect().top,o=i.getBoundingClientRect().top-a;return t.scrollTop+=o-e.offset,{status:`restored`}}readPosition(e){if(e!==``)try{let t=this.storage.getItem($y(e));if(t===null||t===``)return;let n=JSON.parse(t);return eb(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!tb(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function $y(e){return`${Ky}${e}`}function eb(e){return typeof e!=`object`||!e||!(`mode`in e)?!1:e.mode===`bottom`||e.mode===`anchor`&&`anchorId`in e&&typeof e.anchorId==`string`&&e.anchorId!==``&&`offset`in e&&typeof e.offset==`number`}function tb(e){return e.clientHeight>0&&e.scrollHeight>0}function nb(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function rb(e,t=Jy){return nb(e)<t}function ib(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:cb(t)??``,offset:t.getBoundingClientRect().top-n}}function ab(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(cb(e)===void 0)continue;let t=e.getBoundingClientRect();if(t.bottom<=t.top||t.bottom<n.top||t.top>n.bottom)continue;let s=t.top-n.top;s<=0&&s>=i?(r=e,i=s):s>0&&s<o&&(a=e,o=s)}return r??a}function ob(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function sb(e,t){return e.find(e=>cb(e)===t)}function cb(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}function lb(e){let{scrollHeight:t,clientHeight:n,scrollTop:r}=e;if(n<=0||t<=0)return{scrollRatio:0,viewportRatio:1,visible:!1};let i=t-n;return{scrollRatio:i>0?ub(r/i):0,viewportRatio:ub(n/t),visible:!0}}function ub(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function db(e,t){return ub(e*(1-t))}function fb(e,t,n,r){return r<=0?0:ub((e-t+n)/r)}var pb=22,mb=2;function hb(e,t){if(e.length===0)return[];let n=Number.isFinite(t)?Math.max(0,t):0,r=Math.max(0,n-pb),i=e.map((e,t)=>({index:t,desiredTop:ub(e.topRatio)*n-pb/2})).sort((e,t)=>e.desiredTop-t.desiredTop||e.index-t.index),a=Array(e.length).fill(0),o=e=>{for(let t=0;t<i.length;t+=1){let n=i[t],r=e[t];n===void 0||r===void 0||(a[n.index]=Math.round(r))}return a};if(i.length===1)return o([Math.min(r,Math.max(0,i[0]?.desiredTop??0))]);if(i.length*pb+(i.length-1)*mb>n)return o(i.map((e,t)=>r*t/(i.length-1)));let s=i.map(({desiredTop:e})=>Math.min(r,Math.max(0,e)));for(let e=1;e<s.length;e+=1){let t=s[e-1],n=s[e];t===void 0||n===void 0||(s[e]=Math.max(n,t+24))}let c=s.length-1,l=s[c];l!==void 0&&(s[c]=Math.min(l,r));for(let e=c-1;e>=0;--e){let t=s[e+1],n=s[e];t===void 0||n===void 0||(s[e]=Math.min(n,t-24))}return o(s)}function gb(e){if(typeof e!=`object`||!e||!(`ratio`in e))return;let t=e.ratio;if(!(typeof t!=`number`||!Number.isFinite(t)))return ub(t)}function _b(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 vb(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function yb(e){return!Number.isFinite(e)||e===0?`$0.0000`:`$${e.toFixed(4)}`}function bb(e){return Number.isFinite(e)?Math.round(e).toLocaleString():`0`}function xb(e){return Number.isFinite(e)?e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${String(Math.round(e/1e3))}k`:Math.round(e).toString():`0`}function Sb(e){let t=[],n=e.tokens;t.push(`Input: ${bb(n.input)}`),t.push(`Output: ${bb(n.output)}`),t.push(`Cache read: ${bb(n.cacheRead)}`),t.push(`Cache write: ${bb(n.cacheWrite)}`),t.push(`Total: ${bb(n.total)}`),e.cost>0&&t.push(`Cost: ${yb(e.cost)}`);let r=e.contextUsage;if(r!==void 0){let e=r.percent===null?`unknown`:`${r.percent.toFixed(1)}%`;t.push(`Context: ${e} of ${bb(r.contextWindow)} tokens`)}return t.join(` | `)}function Cb(e){let t=0,n=0,r=0,i=0;for(let a of e)a.role===`user`&&(t+=1),a.role===`assistant`&&(n+=1,r+=a.parts.filter(e=>e.type===`toolCall`).length),a.role===`tool`&&(i+=a.parts.filter(e=>e.type===`toolResult`).length);return{user:t,assistant:n,toolCalls:r,toolResults:i,total:e.length}}function wb(e,t,n){let r=[];t?.name!==void 0&&t.name!==``&&r.push({label:`Name`,value:t.name}),r.push({label:`ID`,value:t?.id??e.sessionId,copyValue:t?.id??e.sessionId}),t?.path!==void 0&&t.path!==``?r.push({label:`File`,value:t.path,copyValue:t.path}):t?.persisted===!1?r.push({label:`File`,value:`In-memory (transient)`}):r.push({label:`File`,value:e.persisted===!1?`In-memory (transient)`:`Unknown`});let i=[];n===void 0?e.messageCount!==void 0&&i.push({label:`Total`,value:bb(e.messageCount)}):(i.push({label:`User`,value:bb(n.user)}),i.push({label:`Assistant`,value:bb(n.assistant)}),i.push({label:`Tool calls`,value:bb(n.toolCalls)}),i.push({label:`Tool results`,value:bb(n.toolResults)}),i.push({label:`Total`,value:bb(n.total)}));let a=e.tokens,o=[{label:`Input`,value:bb(a.input)},{label:`Output`,value:bb(a.output)}];a.cacheRead>0&&o.push({label:`Cache read`,value:bb(a.cacheRead)}),a.cacheWrite>0&&o.push({label:`Cache write`,value:bb(a.cacheWrite)}),o.push({label:`Total`,value:bb(a.total)}),e.cost>0&&o.push({label:`Cost`,value:yb(e.cost)});let s=e.contextUsage;if(s!==void 0){let e=s.percent===null?`?`:`${s.percent.toFixed(1)}%`;o.push({label:`Context`,value:`${e} / ${xb(s.contextWindow)}`})}return{sessionRows:r,messageRows:i,tokenRows:o}}var Tb=class extends y{constructor(...e){super(...e),this.scrollRatio=0,this.viewportRatio=1,this.visible=!1,this.loadedPercent=100,this.markers=[],this._hovered=!1,this._nearestIndex=null,this._dragging=!1,this._grabOffset=0}_handlePointerDown(e){if(!this.visible)return;let t=this._rail;if(!t)return;this._dragging=!0,t.setPointerCapture(e.pointerId);let n=t.getBoundingClientRect(),r=ub((e.clientY-n.top)/n.height),i=this._viewportTopRatio(),a=r>=i&&r<=i+this.viewportRatio;this._grabOffset=a?r-i:this.viewportRatio/2,this._dispatchScroll(r-this._grabOffset)}_handlePointerMove(e){if(!this._rail)return;let t=this._rail.getBoundingClientRect(),n=ub((e.clientY-t.top)/t.height);if(this._dragging){this._dispatchScroll(n-this._grabOffset);return}this._nearestIndex=this._findNearestMarker(n)}_handlePointerUp(){this._dragging=!1}_handleKeyDown(e){if(e.key===`ArrowUp`||e.key===`ArrowDown`){e.preventDefault();let t=this.viewportRatio/2,n=e.key===`ArrowUp`?-t:t,r=ub(this._viewportTopRatio()+n);this._dispatchScroll(r)}}_viewportTopRatio(){return db(this.scrollRatio,this.viewportRatio)}_dispatchScroll(e){let t=ub(e);this.dispatchEvent(new CustomEvent(`minimap-scroll-to`,{detail:{ratio:t},bubbles:!0,composed:!0}))}_findNearestMarker(e){let t=this.markers;if(t.length===0)return null;let n=t[0];if(n===void 0)return null;let r=0,i=Math.abs(n.topRatio-e);for(let n=1;n<t.length;n++){let a=t[n];if(a===void 0)continue;let o=Math.abs(a.topRatio-e);o<i&&(i=o,r=n)}return r}render(){return this.visible?g`${this._renderRail()}${this._renderTooltips()}`:g``}_renderRail(){let e=this._viewportTopRatio()*100,t=this.viewportRatio*100,n=this.loadedPercent>=100?`all messages loaded`:`${String(Math.round(this.loadedPercent))}% of messages loaded`;return g`
2351
+ `}};B([x({attribute:!1})],ly.prototype,`tree`,void 0),B([x({attribute:!1})],ly.prototype,`onNavigate`,void 0),B([x({attribute:!1})],ly.prototype,`onAbort`,void 0),B([x({attribute:!1})],ly.prototype,`onCancel`,void 0),B([S()],ly.prototype,`selectedId`,void 0),B([S()],ly.prototype,`foldedIds`,void 0),B([S()],ly.prototype,`step`,void 0),B([S()],ly.prototype,`summaryMode`,void 0),B([S()],ly.prototype,`customInstructions`,void 0),B([S()],ly.prototype,`busy`,void 0),B([S()],ly.prototype,`aborting`,void 0),B([S()],ly.prototype,`error`,void 0),B([S()],ly.prototype,`statusMessage`,void 0),ly=B([b(`session-tree-navigator`)],ly);function uy(e){return Math.min(Math.max(0,e),cy)}function dy(e){return e===`user`||e===`custom-message`}function fy(e){switch(e){case`user`:return`User`;case`assistant`:return`Assistant`;case`tool-result`:return`Tool result`;case`bash`:return`Shell`;case`custom-message`:return`Custom message`;case`compaction`:return`Compaction`;case`branch-summary`:return`Branch summary`;case`model-change`:return`Model`;case`thinking-level-change`:return`Thinking`;case`session-info`:return`Session info`;case`label`:return`Label`;case`custom`:return`Custom`;case`other`:return`Other`}}function py(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function my(e){return e instanceof Error?e.message:String(e)}var hy=`pi-webui:chat-groups:`,gy={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(vy(e));return t===null||t===``?void 0:yy(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(vy(e),JSON.stringify(t))}catch{}}},_y=class{constructor(e=gy){this.storage=e,this.sessionId=``,this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(e){if(this.sessionId===e)return;this.sessionId=e;let t=e===``?void 0:this.storage.read(e);this.openGroupKeys=new Set(t?.open??[]),this.closedDefaultOpenGroupKeys=new Set(t?.closedDefaultOpen??[])}isOpen(e,t){return t?!this.closedDefaultOpenGroupKeys.has(e):this.openGroupKeys.has(e)}applyToggle(e,t,n){let r=this.isOpen(e,n),i=new Set(this.openGroupKeys),a=new Set(this.closedDefaultOpenGroupKeys);return n?(i.delete(e),t?a.delete(e):a.add(e)):(a.delete(e),t?i.add(e):i.delete(e)),(n?!a.has(e):i.has(e))===r&&xy(i,this.openGroupKeys)&&xy(a,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=i,this.closedDefaultOpenGroupKeys=a,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==``&&this.storage.write(this.sessionId,this.snapshot())}};function vy(e){return`${hy}${e}`}function yy(e){if(Array.isArray(e))return{open:by(e),closedDefaultOpen:[]};if(Sy(e))return{open:Array.isArray(e.open)?by(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?by(e.closedDefaultOpen):[]}}function by(e){return e.filter(e=>typeof e==`string`)}function xy(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Sy(e){return typeof e==`object`&&!!e}function Cy(e,t=0){let n=[],r=[],i=0,a=(e,t)=>{r.length||(i=t),r.push(e)},o=()=>{r.length&&(n.push({kind:`group`,messages:r,startIndex:i,endIndex:i+r.length-1}),r=[])};return e.forEach((e,r)=>{let i=e.parts.filter(t=>Dy(e,t)),s=e.parts.filter(t=>!Dy(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}},u={...l,...e.entryId===void 0?{}:{entryId:e.entryId},...e.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:e.previousAssistantEntryId},...e.canFork===void 0?{}:{canFork:e.canFork}};if(s.length&&a({role:e.role,parts:s,...l},c),i.length){o();let t={role:i.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:i,...u};if(Ty(t)){let e=Ey(s);n.push({kind:`tool-image`,message:t,index:c,...e===void 0?{}:{toolName:e}})}else n.push({kind:`message`,message:t,index:c})}}),o(),n}function wy(e){if(e.every(e=>e.source===`compaction`))return`${String(e.length)} history compaction ${e.length===1?`summary`:`summaries`}`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} branch ${e.length===1?`summary`:`summaries`}`;let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n=Object.entries(t).map(([e,t])=>`${String(t)} ${e}`).join(` · `);return`${String(e.length)} ${e.length===1?`event`:`events`}${n===``?``:` · ${n}`}`}function Ty(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function Ey(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function Dy(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}async function Oy(e,t=ky()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function ky(){let e=e=>My(e),t=jy();return t===void 0?{isSecureContext:Ay(),fallbackWriteText:e}:{isSecureContext:Ay(),writeText:t,fallbackWriteText:e}}function Ay(){return typeof window<`u`&&window.isSecureContext}function jy(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function My(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:Ny(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),Py(n,r),Fy(t)}}function Ny(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function Py(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function Fy(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function Iy(e,t){let n=Ry(Vy(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function Ly(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=zy(r,t.markerOffset);return}e.scrollTop=By(e.scrollHeight,t.distanceFromBottom)}function Ry(e){let t,n=-1/0,r,i=1/0;for(let a of e)a.offset<=0&&a.offset>=n?(t=a,n=a.offset):a.offset>0&&a.offset<i&&(r=a,i=a.offset);return t??r}function zy(e,t){return e-t}function By(e,t){return Math.max(0,e-t)}function Vy(e,t){let n=e.getBoundingClientRect().top;return t.flatMap(e=>{let t=e.dataset.markerId;return t===void 0?[]:[{id:t,offset:e.getBoundingClientRect().top-n}]})}var Hy=600,Uy=1;function Wy(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Gy(e)||Ky(e)}function Gy(e){return e.scrollTop<(e.topThreshold??Math.max(Hy,e.clientHeight))}function Ky(e){return e.scrollHeight<=e.clientHeight+Uy}var qy=`pi-webui:chat-scroll:`,Jy=180,Yy=48,Xy=2,Zy={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)}},Qy={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},$y=class{constructor(e=Zy,t=Qy){this.storage=e,this.scheduler=t}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(e,t,n=Jy){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=Xy){if(e===``||t===void 0||!nb(t))return`skipped`;try{if(ib(t,r))return this.storage.setItem(eb(e),JSON.stringify({mode:`bottom`})),`saved`;let i=ob(t,n);if(i===void 0)return`skipped`;let a=ab(t,i);return this.storage.setItem(eb(e),JSON.stringify(a)),`saved`}catch{return`skipped`}}restorePosition(e,t,n,r){let i=this.readPosition(e);return i===void 0?this.scrollToBottom(t):this.restoreExplicitPosition(i,t,n,r)}restoreExplicitPosition(e,t,n,r){if(e.mode===`bottom`)return this.scrollToBottom(t);if(t===void 0||!nb(t))return{status:`skipped`};let i=cb(n,e.anchorId);if(i===void 0)return r?.fallbackToBottom===!1?{status:`missing`,position:e}:this.scrollToBottom(t);let a=t.getBoundingClientRect().top,o=i.getBoundingClientRect().top-a;return t.scrollTop+=o-e.offset,{status:`restored`}}readPosition(e){if(e!==``)try{let t=this.storage.getItem(eb(e));if(t===null||t===``)return;let n=JSON.parse(t);return tb(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!nb(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function eb(e){return`${qy}${e}`}function tb(e){return typeof e!=`object`||!e||!(`mode`in e)?!1:e.mode===`bottom`||e.mode===`anchor`&&`anchorId`in e&&typeof e.anchorId==`string`&&e.anchorId!==``&&`offset`in e&&typeof e.offset==`number`}function nb(e){return e.clientHeight>0&&e.scrollHeight>0}function rb(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function ib(e,t=Yy){return rb(e)<t}function ab(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:lb(t)??``,offset:t.getBoundingClientRect().top-n}}function ob(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(lb(e)===void 0)continue;let t=e.getBoundingClientRect();if(t.bottom<=t.top||t.bottom<n.top||t.top>n.bottom)continue;let s=t.top-n.top;s<=0&&s>=i?(r=e,i=s):s>0&&s<o&&(a=e,o=s)}return r??a}function sb(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function cb(e,t){return e.find(e=>lb(e)===t)}function lb(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}function ub(e){let{scrollHeight:t,clientHeight:n,scrollTop:r}=e;if(n<=0||t<=0)return{scrollRatio:0,viewportRatio:1,visible:!1};let i=t-n;return{scrollRatio:i>0?db(r/i):0,viewportRatio:db(n/t),visible:!0}}function db(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function fb(e,t){return db(e*(1-t))}function pb(e,t,n,r){return r<=0?0:db((e-t+n)/r)}var mb=22,hb=2;function gb(e,t){if(e.length===0)return[];let n=Number.isFinite(t)?Math.max(0,t):0,r=Math.max(0,n-mb),i=e.map((e,t)=>({index:t,desiredTop:db(e.topRatio)*n-mb/2})).sort((e,t)=>e.desiredTop-t.desiredTop||e.index-t.index),a=Array(e.length).fill(0),o=e=>{for(let t=0;t<i.length;t+=1){let n=i[t],r=e[t];n===void 0||r===void 0||(a[n.index]=Math.round(r))}return a};if(i.length===1)return o([Math.min(r,Math.max(0,i[0]?.desiredTop??0))]);if(i.length*mb+(i.length-1)*hb>n)return o(i.map((e,t)=>r*t/(i.length-1)));let s=i.map(({desiredTop:e})=>Math.min(r,Math.max(0,e)));for(let e=1;e<s.length;e+=1){let t=s[e-1],n=s[e];t===void 0||n===void 0||(s[e]=Math.max(n,t+24))}let c=s.length-1,l=s[c];l!==void 0&&(s[c]=Math.min(l,r));for(let e=c-1;e>=0;--e){let t=s[e+1],n=s[e];t===void 0||n===void 0||(s[e]=Math.min(n,t-24))}return o(s)}function _b(e){if(typeof e!=`object`||!e||!(`ratio`in e))return;let t=e.ratio;if(!(typeof t!=`number`||!Number.isFinite(t)))return db(t)}function vb(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 yb(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function bb(e){return!Number.isFinite(e)||e===0?`$0.0000`:`$${e.toFixed(4)}`}function xb(e){return Number.isFinite(e)?Math.round(e).toLocaleString():`0`}function Sb(e){return Number.isFinite(e)?e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${String(Math.round(e/1e3))}k`:Math.round(e).toString():`0`}function Cb(e){let t=[],n=e.tokens;t.push(`Input: ${xb(n.input)}`),t.push(`Output: ${xb(n.output)}`),t.push(`Cache read: ${xb(n.cacheRead)}`),t.push(`Cache write: ${xb(n.cacheWrite)}`),t.push(`Total: ${xb(n.total)}`),e.cost>0&&t.push(`Cost: ${bb(e.cost)}`);let r=e.contextUsage;if(r!==void 0){let e=r.percent===null?`unknown`:`${r.percent.toFixed(1)}%`;t.push(`Context: ${e} of ${xb(r.contextWindow)} tokens`)}return t.join(` | `)}function wb(e){let t=0,n=0,r=0,i=0;for(let a of e)a.role===`user`&&(t+=1),a.role===`assistant`&&(n+=1,r+=a.parts.filter(e=>e.type===`toolCall`).length),a.role===`tool`&&(i+=a.parts.filter(e=>e.type===`toolResult`).length);return{user:t,assistant:n,toolCalls:r,toolResults:i,total:e.length}}function Tb(e,t,n){let r=[];t?.name!==void 0&&t.name!==``&&r.push({label:`Name`,value:t.name}),r.push({label:`ID`,value:t?.id??e.sessionId,copyValue:t?.id??e.sessionId}),t?.path!==void 0&&t.path!==``?r.push({label:`File`,value:t.path,copyValue:t.path}):t?.persisted===!1?r.push({label:`File`,value:`In-memory (transient)`}):r.push({label:`File`,value:e.persisted===!1?`In-memory (transient)`:`Unknown`});let i=[];n===void 0?e.messageCount!==void 0&&i.push({label:`Total`,value:xb(e.messageCount)}):(i.push({label:`User`,value:xb(n.user)}),i.push({label:`Assistant`,value:xb(n.assistant)}),i.push({label:`Tool calls`,value:xb(n.toolCalls)}),i.push({label:`Tool results`,value:xb(n.toolResults)}),i.push({label:`Total`,value:xb(n.total)}));let a=e.tokens,o=[{label:`Input`,value:xb(a.input)},{label:`Output`,value:xb(a.output)}];a.cacheRead>0&&o.push({label:`Cache read`,value:xb(a.cacheRead)}),a.cacheWrite>0&&o.push({label:`Cache write`,value:xb(a.cacheWrite)}),o.push({label:`Total`,value:xb(a.total)}),e.cost>0&&o.push({label:`Cost`,value:bb(e.cost)});let s=e.contextUsage;if(s!==void 0){let e=s.percent===null?`?`:`${s.percent.toFixed(1)}%`;o.push({label:`Context`,value:`${e} / ${Sb(s.contextWindow)}`})}return{sessionRows:r,messageRows:i,tokenRows:o}}var Eb=class extends y{constructor(...e){super(...e),this.scrollRatio=0,this.viewportRatio=1,this.visible=!1,this.loadedPercent=100,this.markers=[],this._hovered=!1,this._nearestIndex=null,this._dragging=!1,this._grabOffset=0}_handlePointerDown(e){if(!this.visible)return;let t=this._rail;if(!t)return;this._dragging=!0,t.setPointerCapture(e.pointerId);let n=t.getBoundingClientRect(),r=db((e.clientY-n.top)/n.height),i=this._viewportTopRatio(),a=r>=i&&r<=i+this.viewportRatio;this._grabOffset=a?r-i:this.viewportRatio/2,this._dispatchScroll(r-this._grabOffset)}_handlePointerMove(e){if(!this._rail)return;let t=this._rail.getBoundingClientRect(),n=db((e.clientY-t.top)/t.height);if(this._dragging){this._dispatchScroll(n-this._grabOffset);return}this._nearestIndex=this._findNearestMarker(n)}_handlePointerUp(){this._dragging=!1}_handleKeyDown(e){if(e.key===`ArrowUp`||e.key===`ArrowDown`){e.preventDefault();let t=this.viewportRatio/2,n=e.key===`ArrowUp`?-t:t,r=db(this._viewportTopRatio()+n);this._dispatchScroll(r)}}_viewportTopRatio(){return fb(this.scrollRatio,this.viewportRatio)}_dispatchScroll(e){let t=db(e);this.dispatchEvent(new CustomEvent(`minimap-scroll-to`,{detail:{ratio:t},bubbles:!0,composed:!0}))}_findNearestMarker(e){let t=this.markers;if(t.length===0)return null;let n=t[0];if(n===void 0)return null;let r=0,i=Math.abs(n.topRatio-e);for(let n=1;n<t.length;n++){let a=t[n];if(a===void 0)continue;let o=Math.abs(a.topRatio-e);o<i&&(i=o,r=n)}return r}render(){return this.visible?g`${this._renderRail()}${this._renderTooltips()}`:g``}_renderRail(){let e=this._viewportTopRatio()*100,t=this.viewportRatio*100,n=this.loadedPercent>=100?`all messages loaded`:`${String(Math.round(this.loadedPercent))}% of messages loaded`;return g`
2346
2352
  <div
2347
2353
  class="rail"
2348
2354
  role="scrollbar"
@@ -2376,7 +2382,7 @@ This will delete every archived session on this machine regardless of age or cle
2376
2382
  class=${`marker-dot${r?` user`:` assistant`}${n?` nearest`:``}`}
2377
2383
  ></div>
2378
2384
  </div>
2379
- `}_renderTooltips(){if(!this._hovered)return null;let e=hb(this.markers,this._rail?.clientHeight??600);return this.markers.map((t,n)=>{let r=e[n];if(t.preview===``||r===void 0)return null;let i=this._nearestIndex===n;return g`
2385
+ `}_renderTooltips(){if(!this._hovered)return null;let e=gb(this.markers,this._rail?.clientHeight??600);return this.markers.map((t,n)=>{let r=e[n];if(t.preview===``||r===void 0)return null;let i=this._nearestIndex===n;return g`
2380
2386
  <div
2381
2387
  class=${`tooltip ${t.role}${i?` nearest`:``}`}
2382
2388
  style=${`top:${String(r)}px`}
@@ -2514,14 +2520,14 @@ This will delete every archived session on this machine regardless of age or cle
2514
2520
  transition: none;
2515
2521
  }
2516
2522
  }
2517
- `}};B([x({type:Number})],Tb.prototype,`scrollRatio`,void 0),B([x({type:Number})],Tb.prototype,`viewportRatio`,void 0),B([x({type:Boolean})],Tb.prototype,`visible`,void 0),B([x({type:Number})],Tb.prototype,`loadedPercent`,void 0),B([x({attribute:!1})],Tb.prototype,`markers`,void 0),B([S()],Tb.prototype,`_hovered`,void 0),B([S()],Tb.prototype,`_nearestIndex`,void 0),B([C(`.rail`)],Tb.prototype,`_rail`,void 0),Tb=B([b(`chat-minimap`)],Tb);var Eb=class extends U_{constructor(e){if(super(e),this.it=v,e.type!==V_.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===v||e==null)return this._t=void 0,this.it=e;if(e===Qe)return e;if(typeof e!=`string`)throw Error(this.constructor.directiveName+`() called with a non-string value`);if(e===this.it)return this._t;this.it=e;let t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}};Eb.directiveName=`unsafeHTML`,Eb.resultType=1;var Db=H_(Eb);function Ob(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var kb=Ob();function Ab(e){kb=e}var jb={exec:()=>null};function Mb(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function W(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Pb.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Nb=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),Pb={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=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Mb(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Mb(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Mb(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Mb(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Mb(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:Mb(e=>RegExp(`^ {0,${e}}>`))},Fb=/^(?:[ \t]*(?:\n|$))+/,Ib=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Lb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Rb=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,zb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Bb=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Vb=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Hb=W(Vb).replace(/bull/g,Bb).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(),Ub=W(Vb).replace(/bull/g,Bb).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(),Wb=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Gb=/^[^\n]+/,Kb=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,qb=W(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Kb).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Jb=W(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Bb).getRegex(),Yb=`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`,Xb=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Zb=W(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n+|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n+|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\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`,Xb).replace(`tag`,Yb).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Qb=e=>W(Wb).replace(`hr`,Rb).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`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Yb).getRegex(),$b=Qb(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),ex=Qb(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),tx={blockquote:W(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,ex).getRegex(),code:Ib,def:qb,fences:Lb,heading:zb,hr:Rb,html:Zb,lheading:Hb,list:Jb,newline:Fb,paragraph:$b,table:jb,text:Gb},nx=W(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,Rb).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`,Yb).getRegex(),rx={...tx,lheading:Ub,table:nx,paragraph:W(Wb).replace(`hr`,Rb).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,nx).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Yb).getRegex()},ix={...tx,html:W(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Xb).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:jb,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:W(Wb).replace(`hr`,Rb).replace(`heading`,` *#{1,6} *[^
2518
- ]`).replace(`lheading`,Hb).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},ax=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ox=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,sx=/^( {2,}|\\)\n(?!\s*$)/,cx=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,lx=/[\p{P}\p{S}]/u,ux=/[\s\p{P}\p{S}]/u,dx=/[^\s\p{P}\p{S}]/u,fx=W(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,ux).getRegex(),px=/(?!~)[\p{P}\p{S}]/u,mx=/(?!~)[\s\p{P}\p{S}]/u,hx=/(?:[^\s\p{P}\p{S}]|~)/u,gx=W(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Nb?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),_x=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,vx=W(_x,`u`).replace(/punct/g,lx).getRegex(),yx=W(_x,`u`).replace(/punct/g,px).getRegex(),bx=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,xx=W(bx,`gu`).replace(/notPunctSpace/g,dx).replace(/punctSpace/g,ux).replace(/punct/g,lx).getRegex(),Sx=W(bx,`gu`).replace(/notPunctSpace/g,hx).replace(/punctSpace/g,mx).replace(/punct/g,px).getRegex(),Cx=W(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,dx).replace(/punctSpace/g,ux).replace(/punct/g,lx).getRegex(),wx=W(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,lx).getRegex(),Tx=W(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,dx).replace(/punctSpace/g,ux).replace(/punct/g,lx).getRegex(),Ex=W(/\\(punct)/,`gu`).replace(/punct/g,lx).getRegex(),Dx=W(/^<(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(),Ox=W(Xb).replace(`(?:-->|$)`,`-->`).getRegex(),kx=W(`^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`,Ox).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ax=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,jx=W(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,Ax).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Mx=W(/^!?\[(label)\]\[(ref)\]/).replace(`label`,Ax).replace(`ref`,Kb).getRegex(),Nx=W(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Kb).getRegex(),Px=W(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Mx).replace(`nolink`,Nx).getRegex(),Fx=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ix={_backpedal:jb,anyPunctuation:Ex,autolink:Dx,blockSkip:gx,br:sx,code:ox,del:jb,delLDelim:jb,delRDelim:jb,emStrongLDelim:vx,emStrongRDelimAst:xx,emStrongRDelimUnd:Cx,escape:ax,link:jx,nolink:Nx,punctuation:fx,reflink:Mx,reflinkSearch:Px,tag:kx,text:cx,url:jb},Lx={...Ix,link:W(/^!?\[(label)\]\((.*?)\)/).replace(`label`,Ax).getRegex(),reflink:W(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,Ax).getRegex()},Rx={...Ix,emStrongRDelimAst:Sx,emStrongLDelim:yx,delLDelim:wx,delRDelim:Tx,url:W(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Fx).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:W(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,Fx).getRegex()},zx={...Rx,br:W(sx).replace(`{2,}`,`*`).getRegex(),text:W(Rx.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},Bx={normal:tx,gfm:rx,pedantic:ix},Vx={normal:Ix,gfm:Rx,breaks:zx,pedantic:Lx},Hx={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},Ux=e=>Hx[e];function Wx(e,t){if(t){if(Pb.escapeTest.test(e))return e.replace(Pb.escapeReplace,Ux)}else if(Pb.escapeTestNoEncode.test(e))return e.replace(Pb.escapeReplaceNoEncode,Ux);return e}function Gx(e){try{e=encodeURI(e).replace(Pb.percentDecode,`%`)}catch{return null}return e}function Kx(e,t){let n=e.replace(Pb.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Pb.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(Pb.slashPipe,`|`);return n}function qx(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function Jx(e){let t=e.split(`
2519
- `),n=t.length-1;for(;n>=0&&Pb.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
2520
- `)}function Yx(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function Xx(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Zx(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function Qx(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
2523
+ `}};B([x({type:Number})],Eb.prototype,`scrollRatio`,void 0),B([x({type:Number})],Eb.prototype,`viewportRatio`,void 0),B([x({type:Boolean})],Eb.prototype,`visible`,void 0),B([x({type:Number})],Eb.prototype,`loadedPercent`,void 0),B([x({attribute:!1})],Eb.prototype,`markers`,void 0),B([S()],Eb.prototype,`_hovered`,void 0),B([S()],Eb.prototype,`_nearestIndex`,void 0),B([C(`.rail`)],Eb.prototype,`_rail`,void 0),Eb=B([b(`chat-minimap`)],Eb);var Db=class extends U_{constructor(e){if(super(e),this.it=v,e.type!==V_.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===v||e==null)return this._t=void 0,this.it=e;if(e===Qe)return e;if(typeof e!=`string`)throw Error(this.constructor.directiveName+`() called with a non-string value`);if(e===this.it)return this._t;this.it=e;let t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}};Db.directiveName=`unsafeHTML`,Db.resultType=1;var Ob=H_(Db);function kb(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ab=kb();function jb(e){Ab=e}var Mb={exec:()=>null};function Nb(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function U(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Fb.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Pb=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),Fb={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=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Nb(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Nb(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Nb(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Nb(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Nb(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:Nb(e=>RegExp(`^ {0,${e}}>`))},Ib=/^(?:[ \t]*(?:\n|$))+/,Lb=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Rb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,zb=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Bb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Vb=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Hb=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ub=U(Hb).replace(/bull/g,Vb).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(),Wb=U(Hb).replace(/bull/g,Vb).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(),Gb=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Kb=/^[^\n]+/,qb=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Jb=U(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,qb).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Yb=U(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Vb).getRegex(),Xb=`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`,Zb=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Qb=U(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n+|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n+|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\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`,Zb).replace(`tag`,Xb).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),$b=e=>U(Gb).replace(`hr`,zb).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`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Xb).getRegex(),ex=$b(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),tx=$b(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),nx={blockquote:U(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,tx).getRegex(),code:Lb,def:Jb,fences:Rb,heading:Bb,hr:zb,html:Qb,lheading:Ub,list:Yb,newline:Ib,paragraph:ex,table:Mb,text:Kb},rx=U(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,zb).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`,Xb).getRegex(),ix={...nx,lheading:Wb,table:rx,paragraph:U(Gb).replace(`hr`,zb).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,rx).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Xb).getRegex()},ax={...nx,html:U(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Zb).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:Mb,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:U(Gb).replace(`hr`,zb).replace(`heading`,` *#{1,6} *[^
2524
+ ]`).replace(`lheading`,Ub).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},ox=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,sx=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,cx=/^( {2,}|\\)\n(?!\s*$)/,lx=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ux=/[\p{P}\p{S}]/u,dx=/[\s\p{P}\p{S}]/u,fx=/[^\s\p{P}\p{S}]/u,px=U(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,dx).getRegex(),mx=/(?!~)[\p{P}\p{S}]/u,hx=/(?!~)[\s\p{P}\p{S}]/u,gx=/(?:[^\s\p{P}\p{S}]|~)/u,_x=U(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Pb?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),vx=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,yx=U(vx,`u`).replace(/punct/g,ux).getRegex(),bx=U(vx,`u`).replace(/punct/g,mx).getRegex(),xx=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,Sx=U(xx,`gu`).replace(/notPunctSpace/g,fx).replace(/punctSpace/g,dx).replace(/punct/g,ux).getRegex(),Cx=U(xx,`gu`).replace(/notPunctSpace/g,gx).replace(/punctSpace/g,hx).replace(/punct/g,mx).getRegex(),wx=U(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,fx).replace(/punctSpace/g,dx).replace(/punct/g,ux).getRegex(),Tx=U(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,ux).getRegex(),Ex=U(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,fx).replace(/punctSpace/g,dx).replace(/punct/g,ux).getRegex(),Dx=U(/\\(punct)/,`gu`).replace(/punct/g,ux).getRegex(),Ox=U(/^<(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(),kx=U(Zb).replace(`(?:-->|$)`,`-->`).getRegex(),Ax=U(`^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`,kx).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),jx=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Mx=U(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,jx).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Nx=U(/^!?\[(label)\]\[(ref)\]/).replace(`label`,jx).replace(`ref`,qb).getRegex(),Px=U(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,qb).getRegex(),Fx=U(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Nx).replace(`nolink`,Px).getRegex(),Ix=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Lx={_backpedal:Mb,anyPunctuation:Dx,autolink:Ox,blockSkip:_x,br:cx,code:sx,del:Mb,delLDelim:Mb,delRDelim:Mb,emStrongLDelim:yx,emStrongRDelimAst:Sx,emStrongRDelimUnd:wx,escape:ox,link:Mx,nolink:Px,punctuation:px,reflink:Nx,reflinkSearch:Fx,tag:Ax,text:lx,url:Mb},Rx={...Lx,link:U(/^!?\[(label)\]\((.*?)\)/).replace(`label`,jx).getRegex(),reflink:U(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,jx).getRegex()},zx={...Lx,emStrongRDelimAst:Cx,emStrongLDelim:bx,delLDelim:Tx,delRDelim:Ex,url:U(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Ix).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:U(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,Ix).getRegex()},Bx={...zx,br:U(cx).replace(`{2,}`,`*`).getRegex(),text:U(zx.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},Vx={normal:nx,gfm:ix,pedantic:ax},Hx={normal:Lx,gfm:zx,breaks:Bx,pedantic:Rx},Ux={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},Wx=e=>Ux[e];function Gx(e,t){if(t){if(Fb.escapeTest.test(e))return e.replace(Fb.escapeReplace,Wx)}else if(Fb.escapeTestNoEncode.test(e))return e.replace(Fb.escapeReplaceNoEncode,Wx);return e}function Kx(e){try{e=encodeURI(e).replace(Fb.percentDecode,`%`)}catch{return null}return e}function qx(e,t){let n=e.replace(Fb.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Fb.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(Fb.slashPipe,`|`);return n}function Jx(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function Yx(e){let t=e.split(`
2525
+ `),n=t.length-1;for(;n>=0&&Fb.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
2526
+ `)}function Xx(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function Zx(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Qx(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function $x(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
2521
2527
  `).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
2522
- `)}var $x=class{options;rules;lexer;constructor(e){this.options=e||kb}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 e=this.options.pedantic?t[0]:Jx(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=Qx(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=qx(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:qx(t[0],`
2523
- `),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:qx(t[0],`
2524
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=qx(t[0],`
2528
+ `)}var eS=class{options;rules;lexer;constructor(e){this.options=e||Ab}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 e=this.options.pedantic?t[0]:Yx(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=$x(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=Jx(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:Jx(t[0],`
2529
+ `),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:Jx(t[0],`
2530
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=Jx(t[0],`
2525
2531
  `).split(`
2526
2532
  `),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o;for(o=0;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
2527
2533
  `),c=s.replace(this.rules.other.blockquoteSetextReplace,`
@@ -2532,20 +2538,20 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
2532
2538
  `),o=this.blockquote(a);i[i.length-1]=o,n=n.substring(0,n.length-t.raw.length)+o.raw,r=r.substring(0,r.length-t.text.length)+o.text;break}else if(u?.type===`list`){let t=u,a=t.raw+`
2533
2539
  `+e.join(`
2534
2540
  `),o=this.list(a);i[i.length-1]=o,n=n.substring(0,n.length-u.raw.length)+o.raw,r=r.substring(0,r.length-t.raw.length)+o.raw,e=a.substring(i.at(-1).raw.length).split(`
2535
- `);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=Xx(t[2].split(`
2541
+ `);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=Zx(t[2].split(`
2536
2542
  `,1)[0],t[1].length),l=e.split(`
2537
2543
  `,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=c.search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+`
2538
2544
  `,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d),f=this.rules.other.blockquoteBeginRegex(d);for(;e;){let p=e.split(`
2539
2545
  `,1)[0],m;if(l=p,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),m=l):m=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||f.test(l)||t.test(l)||n.test(l))break;if(m.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=`
2540
2546
  `+m.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=`
2541
2547
  `+l}u=!l.trim(),r+=p+`
2542
- `,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]);let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1;if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=Jx(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:qx(t[0],`
2543
- `),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Kx(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
2544
- `):[],a={type:`table`,raw:qx(t[0],`
2545
- `),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(Kx(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:qx(t[0],`
2548
+ `,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]);let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1;if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=Yx(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:Jx(t[0],`
2549
+ `),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=qx(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
2550
+ `):[],a={type:`table`,raw:Jx(t[0],`
2551
+ `),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(qx(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:Jx(t[0],`
2546
2552
  `),depth:t[2].charAt(0)===`=`?1:2,text:e,tokens:this.lexer.inline(e)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
2547
- `?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}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 e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=qx(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Yx(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),Zx(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return Zx(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}else if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},eS=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||kb,this.options.tokenizer=this.options.tokenizer||new $x,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 t={other:Pb,block:Bx.normal,inline:Vx.normal};this.options.pedantic?(t.block=Bx.pedantic,t.inline=Vx.pedantic):this.options.gfm&&(t.block=Bx.gfm,this.options.breaks?t.inline=Vx.breaks:t.inline=Vx.gfm),this.tokenizer.rules=t}static get rules(){return{block:Bx,inline:Vx}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(Pb.carriageReturn,`
2548
- `),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Pb.tabCharGlobal,` `).replace(Pb.spaceLine,``));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(n=>(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=`
2553
+ `?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}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 e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=Jx(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Xx(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),Qx(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return Qx(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}else if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},tS=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Ab,this.options.tokenizer=this.options.tokenizer||new eS,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 t={other:Fb,block:Vx.normal,inline:Hx.normal};this.options.pedantic?(t.block=Vx.pedantic,t.inline=Hx.pedantic):this.options.gfm&&(t.block=Vx.gfm,this.options.breaks?t.inline=Hx.breaks:t.inline=Hx.gfm),this.tokenizer.rules=t}static get rules(){return{block:Vx,inline:Hx}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(Fb.carriageReturn,`
2554
+ `),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Fb.tabCharGlobal,` `).replace(Fb.spaceLine,``));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(n=>(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=`
2549
2555
  `:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
2550
2556
  `)?``:`
2551
2557
  `)+i.raw,n.text+=`
@@ -2558,9 +2564,9 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
2558
2564
  `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
2559
2565
  `)?``:`
2560
2566
  `)+i.raw,n.text+=`
2561
- `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``,s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},tS=class{options;parser;constructor(e){this.options=e||kb}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Pb.notSpaceStart)?.[0],i=e.replace(Pb.endingNewline,``)+`
2562
- `;return r?`<pre><code class="language-`+Wx(r)+`">`+(n?i:Wx(i,!0))+`</code></pre>
2563
- `:`<pre><code>`+(n?i:Wx(i,!0))+`</code></pre>
2567
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``,s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},nS=class{options;parser;constructor(e){this.options=e||Ab}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Fb.notSpaceStart)?.[0],i=e.replace(Fb.endingNewline,``)+`
2568
+ `;return r?`<pre><code class="language-`+Gx(r)+`">`+(n?i:Gx(i,!0))+`</code></pre>
2569
+ `:`<pre><code>`+(n?i:Gx(i,!0))+`</code></pre>
2564
2570
  `}blockquote({tokens:e}){return`<blockquote>
2565
2571
  ${this.parser.parse(e)}</blockquote>
2566
2572
  `}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
@@ -2576,19 +2582,19 @@ ${this.parser.parse(e)}</blockquote>
2576
2582
  `}tablerow({text:e}){return`<tr>
2577
2583
  ${e}</tr>
2578
2584
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
2579
- `}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>${Wx(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=Gx(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+Wx(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Gx(e);if(i===null)return Wx(n);e=i;let a=`<img src="${e}" alt="${Wx(n)}"`;return t&&(a+=` title="${Wx(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:Wx(e.text)}},nS=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}},rS=class e{options;renderer;textRenderer;constructor(e){this.options=e||kb,this.options.renderer=this.options.renderer||new tS,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new nS}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},iS=class{options;block;constructor(e){this.options=e||kb}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?eS.lex:eS.lexInline}provideParser(e=this.block){return e?rS.parse:rS.parseInline}},aS=new class{defaults=Ob();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=rS;Renderer=tS;TextRenderer=nS;Lexer=eS;Tokenizer=$x;Hooks=iS;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new tS(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new $x(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new iS;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];iS.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&iS.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return eS.lex(e,t??this.defaults)}parser(e,t){return rS.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(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 a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?eS.lex:eS.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?rS.parse:rS.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?eS.lex:eS.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?rS.parse:rS.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
2580
- Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+Wx(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function G(e,t){return aS.parse(e,t)}G.options=G.setOptions=function(e){return aS.setOptions(e),G.defaults=aS.defaults,Ab(G.defaults),G},G.getDefaults=Ob,G.defaults=kb,G.use=function(...e){return aS.use(...e),G.defaults=aS.defaults,Ab(G.defaults),G},G.walkTokens=function(e,t){return aS.walkTokens(e,t)},G.parseInline=aS.parseInline,G.Parser=rS,G.parser=rS.parse,G.Renderer=tS,G.TextRenderer=nS,G.Lexer=eS,G.lexer=eS.lex,G.Tokenizer=$x,G.Hooks=iS,G.parse=G,G.options,G.setOptions,G.use,G.walkTokens,G.parseInline,rS.parse,eS.lex;var oS=new G.Renderer;oS.html=({text:e})=>uS(e);var sS=300,cS=new Map;function lS(e){let t=cS.get(e);if(t!==void 0)return t;let n=dS(G.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:oS}));if(cS.set(e,n),cS.size>sS){let e=cS.keys().next().value;e!==void 0&&cS.delete(e)}return n}function uS(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function dS(e){let t=document.createElement(`template`);return t.innerHTML=e,t.content.querySelectorAll(`script, style, iframe, object, embed`).forEach(e=>{e.remove()}),t.content.querySelectorAll(`*`).forEach(e=>{for(let t of[...e.attributes]){let n=t.name.toLowerCase();n.startsWith(`on`)&&e.removeAttribute(t.name),(n===`href`||n===`src`)&&!fS(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),t.innerHTML}function fS(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var pS=class extends y{constructor(...e){super(...e),this.text=``,this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`.code-copy-button`);if(!(t instanceof HTMLButtonElement))return;let n=t.closest(`.code-block-wrapper`);if(!(n instanceof HTMLElement))return;let r=n.querySelector(`pre code`);r instanceof HTMLElement&&this.copyCode(r.textContent,t)}}render(){return g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${Db(lS(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;let t=document.createElement(`div`);t.className=`code-block-wrapper`;let n=document.createElement(`button`);n.type=`button`,n.className=`code-copy-button`,n.title=`Copy code block`,n.setAttribute(`aria-label`,`Copy code block`);let r=document.createElement(`span`);r.setAttribute(`aria-hidden`,`true`),r.textContent=`⧉`,n.append(r),e.before(t),t.append(e,n)})}async copyCode(e,t){let n=await Dy(e);this.setCopyButtonState(t,n?`copied`:`failed`),window.setTimeout(()=>{this.setCopyButtonState(t,`idle`)},1200)}setCopyButtonState(e,t){let n=e.querySelector(`span`);n!==null&&(n.textContent=t===`copied`?`✓`:`⧉`);let r=t===`copied`?`Copied code block`:t===`failed`?`Failed to copy code block`:`Copy code block`;e.title=r,e.setAttribute(`aria-label`,r)}static{this.styles=mm}};B([x()],pS.prototype,`text`,void 0),pS=B([b(`formatted-text`)],pS);var mS=180,hS=class extends y{constructor(...e){super(...e),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){let e=this.execution;if(e===void 0)return null;let t=_S(e.args),n=yS(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:bS(i),o=n!==void 0&&r?.diff!==void 0&&n!==r.diff,s=e.status===`error`?e.resultText:r?.error,c=i===void 0?e.resultText:void 0,l=gS(e,t);return g`
2585
+ `}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>${Gx(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=Kx(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+Gx(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Kx(e);if(i===null)return Gx(n);e=i;let a=`<img src="${e}" alt="${Gx(n)}"`;return t&&(a+=` title="${Gx(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:Gx(e.text)}},rS=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},iS=class e{options;renderer;textRenderer;constructor(e){this.options=e||Ab,this.options.renderer=this.options.renderer||new nS,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new rS}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},aS=class{options;block;constructor(e){this.options=e||Ab}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?tS.lex:tS.lexInline}provideParser(e=this.block){return e?iS.parse:iS.parseInline}},oS=new class{defaults=kb();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=iS;Renderer=nS;TextRenderer=rS;Lexer=tS;Tokenizer=eS;Hooks=aS;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new nS(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new eS(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new aS;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];aS.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&aS.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return tS.lex(e,t??this.defaults)}parser(e,t){return iS.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(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 a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?tS.lex:tS.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?iS.parse:iS.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?tS.lex:tS.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?iS.parse:iS.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
2586
+ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+Gx(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function W(e,t){return oS.parse(e,t)}W.options=W.setOptions=function(e){return oS.setOptions(e),W.defaults=oS.defaults,jb(W.defaults),W},W.getDefaults=kb,W.defaults=Ab,W.use=function(...e){return oS.use(...e),W.defaults=oS.defaults,jb(W.defaults),W},W.walkTokens=function(e,t){return oS.walkTokens(e,t)},W.parseInline=oS.parseInline,W.Parser=iS,W.parser=iS.parse,W.Renderer=nS,W.TextRenderer=rS,W.Lexer=tS,W.lexer=tS.lex,W.Tokenizer=eS,W.Hooks=aS,W.parse=W,W.options,W.setOptions,W.use,W.walkTokens,W.parseInline,iS.parse,tS.lex;var sS=new W.Renderer;sS.html=({text:e})=>dS(e);var cS=300,lS=new Map;function uS(e){let t=lS.get(e);if(t!==void 0)return t;let n=fS(W.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:sS}));if(lS.set(e,n),lS.size>cS){let e=lS.keys().next().value;e!==void 0&&lS.delete(e)}return n}function dS(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function fS(e){let t=document.createElement(`template`);return t.innerHTML=e,t.content.querySelectorAll(`script, style, iframe, object, embed`).forEach(e=>{e.remove()}),t.content.querySelectorAll(`*`).forEach(e=>{for(let t of[...e.attributes]){let n=t.name.toLowerCase();n.startsWith(`on`)&&e.removeAttribute(t.name),(n===`href`||n===`src`)&&!pS(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),t.innerHTML}function pS(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var mS=class extends y{constructor(...e){super(...e),this.text=``,this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`.code-copy-button`);if(!(t instanceof HTMLButtonElement))return;let n=t.closest(`.code-block-wrapper`);if(!(n instanceof HTMLElement))return;let r=n.querySelector(`pre code`);r instanceof HTMLElement&&this.copyCode(r.textContent,t)}}render(){return g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${Ob(uS(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;let t=document.createElement(`div`);t.className=`code-block-wrapper`;let n=document.createElement(`button`);n.type=`button`,n.className=`code-copy-button`,n.title=`Copy code block`,n.setAttribute(`aria-label`,`Copy code block`);let r=document.createElement(`span`);r.setAttribute(`aria-hidden`,`true`),r.textContent=`⧉`,n.append(r),e.before(t),t.append(e,n)})}async copyCode(e,t){let n=await Oy(e);this.setCopyButtonState(t,n?`copied`:`failed`),window.setTimeout(()=>{this.setCopyButtonState(t,`idle`)},1200)}setCopyButtonState(e,t){let n=e.querySelector(`span`);n!==null&&(n.textContent=t===`copied`?`✓`:`⧉`);let r=t===`copied`?`Copied code block`:t===`failed`?`Failed to copy code block`:`Copy code block`;e.title=r,e.setAttribute(`aria-label`,r)}static{this.styles=mm}};B([x()],mS.prototype,`text`,void 0),mS=B([b(`formatted-text`)],mS);var hS=180,gS=class extends y{constructor(...e){super(...e),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){let e=this.execution;if(e===void 0)return null;let t=vS(e.args),n=bS(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:xS(i),o=n!==void 0&&r?.diff!==void 0&&n!==r.diff,s=e.status===`error`?e.resultText:r?.error,c=i===void 0?e.resultText:void 0,l=_S(e,t);return g`
2581
2587
  <section class=${`tool-card ${e.status}`}>
2582
2588
  <div class="tool-header">
2583
2589
  <div class="tool-title">
2584
- <span class="status-icon" aria-hidden="true">${wS(e.status)}</span>
2590
+ <span class="status-icon" aria-hidden="true">${TS(e.status)}</span>
2585
2591
  <strong>${e.toolName}</strong>
2586
2592
  ${this.renderHeaderTarget(l)}
2587
2593
  </div>
2588
2594
  <div class="tool-meta">
2589
- ${vS(e)===void 0?null:g`<span>${vS(e)}</span>`}
2595
+ ${yS(e)===void 0?null:g`<span>${yS(e)}</span>`}
2590
2596
  ${a===void 0?null:g`<span class="diff-stats"><b class="added">+${a.added}</b><span>/</span><b class="removed">-${a.removed}</b></span>`}
2591
- <span class="status-label">${TS(e.status)}</span>
2597
+ <span class="status-label">${ES(e.status)}</span>
2592
2598
  </div>
2593
2599
  </div>
2594
2600
 
@@ -2613,7 +2619,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2613
2619
  `}
2614
2620
  </details>
2615
2621
  `}renderDiffBody(e,t,n){let r=e.split(`
2616
- `),i=!this.showFullDiff&&r.length>mS,a=i?r.slice(0,mS):r;return g`
2622
+ `),i=!this.showFullDiff&&r.length>hS,a=i?r.slice(0,hS):r;return g`
2617
2623
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
2618
2624
  <summary>
2619
2625
  <span>${t}</span>
@@ -2624,14 +2630,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2624
2630
  <span>${i?`Showing ${String(a.length)} of ${String(r.length)} lines`:`Full diff`}</span>
2625
2631
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?`Copied`:`Copy diff`}</button>
2626
2632
  </div>
2627
- <pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${xS(e)}>${e}</span>`)}</code></pre>
2633
+ <pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${SS(e)}>${e}</span>`)}</code></pre>
2628
2634
  ${i?g`
2629
2635
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
2630
2636
  Show all ${String(r.length)} diff lines
2631
2637
  </button>
2632
2638
  `:null}
2633
2639
  </details>
2634
- `}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await Dy(e)){this.copied=!1;return}this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}static{this.styles=h`
2640
+ `}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await Oy(e)){this.copied=!1;return}this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}static{this.styles=h`
2635
2641
  :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
2636
2642
  .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); }
2637
2643
  .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
@@ -2675,18 +2681,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2675
2681
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
2676
2682
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
2677
2683
  .show-more { justify-self: start; }
2678
- `}};B([x({attribute:!1})],hS.prototype,`execution`,void 0),B([S()],hS.prototype,`showFullDiff`,void 0),B([S()],hS.prototype,`copied`,void 0),B([S()],hS.prototype,`diffOpen`,void 0),hS=B([b(`tool-execution-view`)],hS);function gS(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=OS(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function _S(e){return OS(e,`path`)??OS(e,`file_path`)}function vS(e){if(e.toolName!==`edit`)return;let t=DS(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof DS(e.args,`oldText`)==`string`&&typeof DS(e.args,`newText`)==`string`)return`1 edit`}function yS(e){return OS(e,`diff`)}function bS(e){let t=0,n=0;for(let r of e.split(`
2679
- `))SS(r)?t++:CS(r)&&n++;return{added:t,removed:n}}function xS(e){return SS(e)?`added`:CS(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function SS(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function CS(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function wS(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function TS(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function ES(e){return typeof e==`object`&&!!e}function DS(e,t){return ES(e)?e[t]:void 0}function OS(e,t){let n=DS(e,t);return typeof n==`string`?n:void 0}var kS=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),AS=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function jS(e){return g`
2684
+ `}};B([x({attribute:!1})],gS.prototype,`execution`,void 0),B([S()],gS.prototype,`showFullDiff`,void 0),B([S()],gS.prototype,`copied`,void 0),B([S()],gS.prototype,`diffOpen`,void 0),gS=B([b(`tool-execution-view`)],gS);function _S(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=kS(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function vS(e){return kS(e,`path`)??kS(e,`file_path`)}function yS(e){if(e.toolName!==`edit`)return;let t=OS(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof OS(e.args,`oldText`)==`string`&&typeof OS(e.args,`newText`)==`string`)return`1 edit`}function bS(e){return kS(e,`diff`)}function xS(e){let t=0,n=0;for(let r of e.split(`
2685
+ `))CS(r)?t++:wS(r)&&n++;return{added:t,removed:n}}function SS(e){return CS(e)?`added`:wS(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function CS(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function wS(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function TS(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function ES(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function DS(e){return typeof e==`object`&&!!e}function OS(e,t){return DS(e)?e[t]:void 0}function kS(e,t){let n=OS(e,t);return typeof n==`string`?n:void 0}var AS=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),jS=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function MS(e){return g`
2680
2686
  <svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2681
2687
  <path d="m9 18 6-6-6-6"></path>
2682
2688
  </svg>
2683
- `}function MS(){return g`
2689
+ `}function NS(){return g`
2684
2690
  <svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2685
2691
  <path d="M6 6l12 12"></path>
2686
2692
  <path d="M18 6 6 18"></path>
2687
2693
  </svg>
2688
- `}function NS(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`machineId`)==`string`&&typeof Reflect.get(e,`cwd`)==`string`&&typeof Reflect.get(e,`sessionId`)==`string`}function PS(e){return FS(e,0,100)}function FS(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function IS(e,t){return[e.length===0?void 0:{source:`client`,heading:`Queued until session starts`,detail:`Will send once the backend session is ready`,messages:e},t.length===0?void 0:{source:`server`,heading:`Queued messages`,detail:`${String(t.length)} pending`,messages:t}].filter(e=>e!==void 0)}function LS(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function RS(e){return e===void 0||e===``?`tool output`:`${e} output`}function zS(e){return`m:${String(e)}`}function BS(e){return`g:${String(e)}`}function VS(e){return`e:${String(e)}`}function HS(e){return`g:${String(e)}`}function US(e){return e?`msg event-group live`:`msg event-group`}function WS(e){return e?`live events`:`events`}function GS(e,t,n){return e.source===`server`&&t&&n}function KS(e){return(e?.warnings??[]).map(e=>({severity:e.severity,severityClass:`session-warning ${e.severity}`,message:e.message,...e.source===void 0?{}:{source:e.source},...e.path===void 0?{}:{path:e.path},...e.dismiss===void 0?{}:{dismissId:e.dismiss.id}}))}function qS(e){return e>=50?`generation-rate very-fast`:e>=30?`generation-rate fast`:e>=15?`generation-rate moderate`:`generation-rate slow`}function JS(e){if(e===void 0)return{afterStatus:[],trailing:[]};let t=e.contextUsage,n=t?t.percent==null?`context ${_b(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${_b(t.contextWindow)}`:`context unknown`,r=e.generation;return{afterStatus:!e.isStreaming||r===void 0||!Number.isFinite(r.outputTokens)||r.outputTokens<=0?[]:[{label:r.estimated===!0?`Estimated received tokens`:`Received tokens`,text:`↓ ${_b(r.outputTokens)}`},...r.tokensPerSecond===void 0||!Number.isFinite(r.tokensPerSecond)||r.tokensPerSecond<=0?[]:[{label:r.estimated===!0?`Estimated generation speed`:`Generation speed`,text:`${r.tokensPerSecond.toFixed(1)} t/s`,className:qS(r.tokensPerSecond)}]],trailing:[{label:`Input tokens`,text:`↑${_b(e.tokens.input)}`},{label:`Output tokens`,text:`↓${_b(e.tokens.output)}`},{label:`Context usage`,text:n},{label:`Session cost`,text:vb(e.cost)},...e.pendingMessageCount>0?[{label:`Queued messages`,text:`${String(e.pendingMessageCount)} queued`}]:[]]}}function YS(e,t){if(!Number.isInteger(e)||e<=0)return;let n=`${String(e)} ${e===1?`warning`:`warnings`}`;return{countText:String(e),accessibleLabel:t?`Minimise ${n}`:`Show ${n} in the warning area`}}function XS(e){let t=e.meta?.timestamp,n=[t===void 0?void 0:$S(t),eC(e)].filter(e=>e!==void 0&&e!==``);return n.length===0?`No Pi message metadata available`:n.join(` · `)}function ZS(e,t){return!t.enabled||t.busy||e.role!==`user`?{}:{...e.previousAssistantEntryId===void 0?{}:{editFromHereEntryId:e.previousAssistantEntryId},...e.canFork===!0&&e.entryId!==void 0?{forkEntryId:e.entryId}:{}}}function QS(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
2689
- `)}function $S(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return kS.format(t)}function eC(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var K=class extends y{constructor(...e){super(...e),this.messages=[],this.sessionId=``,this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.clientQueuedMessages=[],this.warningCount=0,this.warningsExpanded=!1,this.canClearServerQueue=!1,this.canMessageActions=!1,this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedNotificationTargetKeys=new Set,this.disclosures=new gy,this.scrollController=new Qy,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.sessionInfoOpen=!1,this._minimapMarkers=[],this._minimapViewport={scrollRatio:0,viewportRatio:1,visible:!1},this._minimapLoadedPercent=100,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onImageLoad=()=>{this.pinnedToBottom&&this.scrollToBottom()},this.openImageZoom=(e,t)=>{this.zoomedImage={src:e,alt:t}},this.closeImageZoom=()=>{this.zoomedImage!==void 0&&(this.zoomedImage=void 0)},this.onImageZoomDialogClick=e=>{e.target===this.imageZoomDialog&&this.closeImageZoom()},this.onPageHide=()=>{this.saveScrollPosition()},this.handleClearServerQueue=()=>{this.onClearServerQueue?.()},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},this.handleUsageToggle=()=>{this.sessionInfoOpen=!this.sessionInfoOpen},this.handleUsageKeydown=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.sessionInfoOpen=!this.sessionInfoOpen)},this.closeSessionInfoPopover=()=>{this.sessionInfoOpen&&(this.sessionInfoOpen=!1,this.removePopoverOutsideListener(),this.requestUpdate())},this.handlePopoverKeydown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeSessionInfoPopover(),this.focusUsageToggle())},this.onPopoverGlobalClick=e=>{this.handlePopoverClickOutside(e)},this.popoverGlobalListenerAttached=!1}focusUsageToggle(){this.renderRoot!==void 0&&this.renderRoot.querySelector(`.usage-toggle`)?.focus()}handlePopoverClickOutside(e){let t=this.renderRoot.querySelector(`.session-info-popover`),n=this.renderRoot.querySelector(`.usage-toggle`);if(t===null||n===null)return;let r=e.target;r instanceof Node&&!t.contains(r)&&!n.contains(r)&&this.closeSessionInfoPopover()}ensurePopoverOutsideListener(){this.popoverGlobalListenerAttached||typeof window>`u`||(this.popoverGlobalListenerAttached=!0,window.addEventListener(`click`,this.onPopoverGlobalClick,!0))}removePopoverOutsideListener(){this.popoverGlobalListenerAttached&&(this.popoverGlobalListenerAttached=!1,!(typeof window>`u`)&&window.removeEventListener(`click`,this.onPopoverGlobalClick,!0))}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),window.addEventListener(`pagehide`,this.onPageHide),window.visualViewport?.addEventListener(`resize`,this.onViewportResize),this._setupResizeObserver()}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}_setupResizeObserver(){if(this._resizeObserver!==void 0)return;let e=this.chat;e&&(this._resizeObserver=new ResizeObserver(()=>{this._requestMinimapMeasure()}),this._resizeObserver.observe(e))}disconnectedCallback(){this.removePopoverOutsideListener(),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),this._minimapMeasureTimer!==void 0&&(clearTimeout(this._minimapMeasureTimer),this._minimapMeasureTimer=void 0),this._resizeObserver!==void 0&&(this._resizeObserver.disconnect(),this._resizeObserver=void 0),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.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,this.sessionInfoOpen=!1,this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this._minimapMarkers=[],this._minimapViewport={scrollRatio:0,viewportRatio:1,visible:!1},this._minimapLoadedPercent=100,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(`notificationInbox`)&&this.notificationTargetChanged(e.get(`notificationInbox`))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0),e.has(`messages`)&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){let 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(),this._requestMinimapMeasure()),e.has(`messages`)&&!e.has(`sessionId`)&&this._updateMinimapViewport(),(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(),e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget(),e.has(`zoomedImage`)&&this.syncImageZoomDialog(),this.syncPopoverOutsideListener()}syncPopoverOutsideListener(){this.sessionInfoOpen?this.ensurePopoverOutsideListener():this.removePopoverOutsideListener()}syncImageZoomDialog(){let e=this.imageZoomDialog;e!==void 0&&(this.zoomedImage!==void 0&&!e.open?e.showModal():this.zoomedImage===void 0&&e.open&&e.close())}notificationTargetChanged(e){let t=this.notificationInbox;return!NS(e)||t===void 0?e!==t:Dd(e)!==Dd(t)}render(){let e=this.groupedMessages();return g`
2694
+ `}function PS(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`machineId`)==`string`&&typeof Reflect.get(e,`cwd`)==`string`&&typeof Reflect.get(e,`sessionId`)==`string`}function FS(e){return IS(e,0,100)}function IS(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function LS(e,t){let n=[`steer`,`followUp`].flatMap(e=>{let n=t.filter(t=>t.kind===e);return n.length===0?[]:[{source:`server`,kind:e,heading:e===`steer`?`Steered`:`Follow-up`,detail:e===`steer`?`Sent together at the next turn`:`Sent together after the agent finishes`,messages:n}]});return[e.length===0?void 0:{source:`client`,heading:`Queued until session starts`,detail:`Will send once the backend session is ready`,messages:e},...n].filter(e=>e!==void 0)}function RS(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function zS(e){return e===void 0||e===``?`tool output`:`${e} output`}function BS(e){return`m:${String(e)}`}function VS(e){return`g:${String(e)}`}function HS(e){return`e:${String(e)}`}function US(e){return`g:${String(e)}`}function WS(e){return e?`msg event-group live`:`msg event-group`}function GS(e){return e?`live events`:`events`}function KS(e,t,n){return e.some(e=>e.source===`server`&&e.messages.length>0)&&t&&n}function qS(e){return e.filter(e=>e.source===`server`&&e.messages.length>0).flatMap(e=>e.messages.map(e=>e.text)).join(`
2695
+
2696
+ `)}function JS(e){return(e?.warnings??[]).map(e=>({severity:e.severity,severityClass:`session-warning ${e.severity}`,message:e.message,...e.source===void 0?{}:{source:e.source},...e.path===void 0?{}:{path:e.path},...e.dismiss===void 0?{}:{dismissId:e.dismiss.id}}))}function YS(e){return e>=50?`generation-rate very-fast`:e>=30?`generation-rate fast`:e>=15?`generation-rate moderate`:`generation-rate slow`}function XS(e){if(e===void 0)return{afterStatus:[],trailing:[]};let t=e.contextUsage,n=t?t.percent==null?`context ${vb(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${vb(t.contextWindow)}`:`context unknown`,r=e.generation;return{afterStatus:!e.isStreaming||r===void 0||!Number.isFinite(r.outputTokens)||r.outputTokens<=0?[]:[{label:r.estimated===!0?`Estimated received tokens`:`Received tokens`,text:`↓ ${vb(r.outputTokens)}`},...r.tokensPerSecond===void 0||!Number.isFinite(r.tokensPerSecond)||r.tokensPerSecond<=0?[]:[{label:r.estimated===!0?`Estimated generation speed`:`Generation speed`,text:`${r.tokensPerSecond.toFixed(1)} t/s`,className:YS(r.tokensPerSecond)}]],trailing:[{label:`Input tokens`,text:`↑${vb(e.tokens.input)}`},{label:`Output tokens`,text:`↓${vb(e.tokens.output)}`},{label:`Context usage`,text:n},{label:`Session cost`,text:yb(e.cost)},...e.pendingMessageCount>0?[{label:`Queued messages`,text:`${String(e.pendingMessageCount)} queued`}]:[]]}}function ZS(e,t){if(!Number.isInteger(e)||e<=0)return;let n=`${String(e)} ${e===1?`warning`:`warnings`}`;return{countText:String(e),accessibleLabel:t?`Minimise ${n}`:`Show ${n} in the warning area`}}function QS(e){let t=e.meta?.timestamp,n=[t===void 0?void 0:tC(t),nC(e)].filter(e=>e!==void 0&&e!==``);return n.length===0?`No Pi message metadata available`:n.join(` · `)}function $S(e,t){return!t.enabled||t.busy||e.role!==`user`?{}:{...e.previousAssistantEntryId===void 0?{}:{editFromHereEntryId:e.previousAssistantEntryId},...e.canFork===!0&&e.entryId!==void 0?{forkEntryId:e.entryId}:{}}}function eC(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
2697
+ `)}function tC(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return AS.format(t)}function nC(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var G=class extends y{constructor(...e){super(...e),this.messages=[],this.sessionId=``,this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.clientQueuedMessages=[],this.warningCount=0,this.warningsExpanded=!1,this.canClearServerQueue=!1,this.canMessageActions=!1,this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedNotificationTargetKeys=new Set,this.disclosures=new _y,this.scrollController=new $y,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.sessionInfoOpen=!1,this._minimapMarkers=[],this._minimapViewport={scrollRatio:0,viewportRatio:1,visible:!1},this._minimapLoadedPercent=100,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onImageLoad=()=>{this.pinnedToBottom&&this.scrollToBottom()},this.openImageZoom=(e,t)=>{this.zoomedImage={src:e,alt:t}},this.closeImageZoom=()=>{this.zoomedImage!==void 0&&(this.zoomedImage=void 0)},this.onImageZoomDialogClick=e=>{e.target===this.imageZoomDialog&&this.closeImageZoom()},this.onPageHide=()=>{this.saveScrollPosition()},this.handleClearServerQueue=()=>{this.onClearServerQueue?.()},this.handleCopyAllQueuedMessages=()=>{this.copyAllQueuedMessages()},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},this.handleUsageToggle=()=>{this.sessionInfoOpen=!this.sessionInfoOpen},this.handleUsageKeydown=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.sessionInfoOpen=!this.sessionInfoOpen)},this.closeSessionInfoPopover=()=>{this.sessionInfoOpen&&(this.sessionInfoOpen=!1,this.removePopoverOutsideListener(),this.requestUpdate())},this.handlePopoverKeydown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeSessionInfoPopover(),this.focusUsageToggle())},this.onPopoverGlobalClick=e=>{this.handlePopoverClickOutside(e)},this.popoverGlobalListenerAttached=!1}focusUsageToggle(){this.renderRoot!==void 0&&this.renderRoot.querySelector(`.usage-toggle`)?.focus()}handlePopoverClickOutside(e){let t=this.renderRoot.querySelector(`.session-info-popover`),n=this.renderRoot.querySelector(`.usage-toggle`);if(t===null||n===null)return;let r=e.target;r instanceof Node&&!t.contains(r)&&!n.contains(r)&&this.closeSessionInfoPopover()}ensurePopoverOutsideListener(){this.popoverGlobalListenerAttached||typeof window>`u`||(this.popoverGlobalListenerAttached=!0,window.addEventListener(`click`,this.onPopoverGlobalClick,!0))}removePopoverOutsideListener(){this.popoverGlobalListenerAttached&&(this.popoverGlobalListenerAttached=!1,!(typeof window>`u`)&&window.removeEventListener(`click`,this.onPopoverGlobalClick,!0))}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),window.addEventListener(`pagehide`,this.onPageHide),window.visualViewport?.addEventListener(`resize`,this.onViewportResize),this._setupResizeObserver()}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}_setupResizeObserver(){if(this._resizeObserver!==void 0)return;let e=this.chat;e&&(this._resizeObserver=new ResizeObserver(()=>{this._requestMinimapMeasure()}),this._resizeObserver.observe(e))}disconnectedCallback(){this.removePopoverOutsideListener(),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),this._minimapMeasureTimer!==void 0&&(clearTimeout(this._minimapMeasureTimer),this._minimapMeasureTimer=void 0),this._resizeObserver!==void 0&&(this._resizeObserver.disconnect(),this._resizeObserver=void 0),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.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,this.sessionInfoOpen=!1,this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this._minimapMarkers=[],this._minimapViewport={scrollRatio:0,viewportRatio:1,visible:!1},this._minimapLoadedPercent=100,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(`notificationInbox`)&&this.notificationTargetChanged(e.get(`notificationInbox`))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0),e.has(`messages`)&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){let 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(),this._requestMinimapMeasure()),e.has(`messages`)&&!e.has(`sessionId`)&&this._updateMinimapViewport(),(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(),e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget(),e.has(`zoomedImage`)&&this.syncImageZoomDialog(),this.syncPopoverOutsideListener()}syncPopoverOutsideListener(){this.sessionInfoOpen?this.ensurePopoverOutsideListener():this.removePopoverOutsideListener()}syncImageZoomDialog(){let e=this.imageZoomDialog;e!==void 0&&(this.zoomedImage!==void 0&&!e.open?e.showModal():this.zoomedImage===void 0&&e.open&&e.close())}notificationTargetChanged(e){let t=this.notificationInbox;return!PS(e)||t===void 0?e!==t:Dd(e)!==Dd(t)}render(){let e=this.groupedMessages();return g`
2690
2698
  ${this.renderTopNotices()}
2691
2699
  ${this.renderNotificationLiveRegions()}
2692
2700
  <div class="chat-wrap" style=${this._minimapViewport.visible&&this.messages.length>0&&this.messageTotal>0?`--pi-minimap-right:36px`:``}>
@@ -2721,7 +2729,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2721
2729
  aria-expanded=${String(!a)}
2722
2730
  aria-controls="session-notification-list"
2723
2731
  @click=${()=>{this.toggleNotificationTray(e,a)}}
2724
- >${jS(a)}</button>
2732
+ >${MS(a)}</button>
2725
2733
  </div>
2726
2734
  </header>
2727
2735
  <div class="notification-list" id="session-notification-list" ?hidden=${a}>
@@ -2733,7 +2741,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2733
2741
  <div class="notification-metadata">
2734
2742
  <strong class="notification-severity">${n}</strong>
2735
2743
  <span aria-hidden="true">·</span>
2736
- <time datetime=${t.receivedAt}>${AS.format(new Date(t.receivedAt))}</time>
2744
+ <time datetime=${t.receivedAt}>${jS.format(new Date(t.receivedAt))}</time>
2737
2745
  </div>
2738
2746
  <p class="notification-message" dir="auto">${t.message}</p>
2739
2747
  ${r===void 0?null:g`<p class="notification-truncated">${r}</p>`}
@@ -2744,7 +2752,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2744
2752
  title="Dismiss notification"
2745
2753
  ?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
2746
2754
  @click=${()=>{this.dismissNotification(t.id)}}
2747
- >${MS()}</button>
2755
+ >${NS()}</button>
2748
2756
  </article>
2749
2757
  `})}
2750
2758
  </div>
@@ -2752,7 +2760,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2752
2760
  `}renderNotificationLiveRegions(){let e=this.notificationInbox?.sessionId===this.sessionId?this.notificationInbox.announcements:[],t=e.filter(e=>e.severity!==`error`),n=e.filter(e=>e.severity===`error`);return g`
2753
2761
  <div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${ev(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Sd(e)}</span>`)}</div>
2754
2762
  <div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${ev(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Sd(e)}</span>`)}</div>
2755
- `}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=kd(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=Ed(t.notifications,e),r=Dd(t);this.pendingNotificationFocus={chatKey:r,focusTarget:n},n.kind===`header`&&(this.retainedEmptyNotificationTrayTargetKey=r),this.onDismissNotification(e)}dismissAllNotifications(){let e=this.notificationInbox;if(e===void 0||this.onDismissAllNotifications===void 0)return;let t=Dd(e);this.pendingNotificationFocus={chatKey:t,focusTarget:{kind:`header`}},this.retainedEmptyNotificationTrayTargetKey=t,this.onDismissAllNotifications()}releaseEmptyNotificationTray(e){let t=e.currentTarget,n=e.relatedTarget;if(t instanceof HTMLElement&&n instanceof Node&&t.contains(n)||this.pendingNotificationFocus!==void 0)return;let r=this.notificationInbox;r!==void 0&&this.retainedEmptyNotificationTrayTargetKey===Dd(r)&&Cd(r)===0&&(this.retainedEmptyNotificationTrayTargetKey=void 0)}focusPendingNotificationTarget(){let e=this.pendingNotificationFocus;this.pendingNotificationFocus=void 0;let t=this.notificationInbox;if(e===void 0||t===void 0||Dd(t)!==e.chatKey)return;let n=e.focusTarget;if(n.kind===`header`){this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus();return}let r=Array.from(this.renderRoot.querySelectorAll(`[data-notification-id]`)).find(e=>e.dataset.notificationId===n.notificationId);if(r!==void 0){r.focus();return}Cd(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=KS(this.status);return!this.warningsVisible||e.length===0?null:g`
2763
+ `}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=kd(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=Ed(t.notifications,e),r=Dd(t);this.pendingNotificationFocus={chatKey:r,focusTarget:n},n.kind===`header`&&(this.retainedEmptyNotificationTrayTargetKey=r),this.onDismissNotification(e)}dismissAllNotifications(){let e=this.notificationInbox;if(e===void 0||this.onDismissAllNotifications===void 0)return;let t=Dd(e);this.pendingNotificationFocus={chatKey:t,focusTarget:{kind:`header`}},this.retainedEmptyNotificationTrayTargetKey=t,this.onDismissAllNotifications()}releaseEmptyNotificationTray(e){let t=e.currentTarget,n=e.relatedTarget;if(t instanceof HTMLElement&&n instanceof Node&&t.contains(n)||this.pendingNotificationFocus!==void 0)return;let r=this.notificationInbox;r!==void 0&&this.retainedEmptyNotificationTrayTargetKey===Dd(r)&&Cd(r)===0&&(this.retainedEmptyNotificationTrayTargetKey=void 0)}focusPendingNotificationTarget(){let e=this.pendingNotificationFocus;this.pendingNotificationFocus=void 0;let t=this.notificationInbox;if(e===void 0||t===void 0||Dd(t)!==e.chatKey)return;let n=e.focusTarget;if(n.kind===`header`){this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus();return}let r=Array.from(this.renderRoot.querySelectorAll(`[data-notification-id]`)).find(e=>e.dataset.notificationId===n.notificationId);if(r!==void 0){r.focus();return}Cd(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=JS(this.status);return!this.warningsVisible||e.length===0?null:g`
2756
2764
  <aside class="session-warnings" role="alert" aria-live="polite">
2757
2765
  ${e.map(e=>{let t=e.dismissId;return g`
2758
2766
  <div class=${e.severityClass}>
@@ -2776,7 +2784,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2776
2784
  </div>
2777
2785
  `})}
2778
2786
  </aside>
2779
- `}renderSessionInfoPopover(){if(!this.sessionInfoOpen)return null;let e=this.status;if(e===void 0)return null;let t=this.messages.length>0?Cb(this.messages):void 0,n=wb(e,this.sessionInfo,t);return g`
2787
+ `}renderSessionInfoPopover(){if(!this.sessionInfoOpen)return null;let e=this.status;if(e===void 0)return null;let t=this.messages.length>0?wb(this.messages):void 0,n=Tb(e,this.sessionInfo,t);return g`
2780
2788
  <section
2781
2789
  class="session-info-popover"
2782
2790
  id=${`session-info-popover-${this.sessionId}`}
@@ -2826,14 +2834,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2826
2834
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
2827
2835
  </svg>
2828
2836
  </button>
2829
- `}async copySessionValue(e){await Dy(e)}renderImageZoom(){return g`
2837
+ `}async copySessionValue(e){await Oy(e)}renderImageZoom(){return g`
2830
2838
  <dialog class="image-zoom" @click=${this.onImageZoomDialogClick} @close=${this.closeImageZoom} @cancel=${this.closeImageZoom}>
2831
2839
  ${this.zoomedImage===void 0?null:g`
2832
2840
  <button type="button" class="image-zoom-close" aria-label="Close image" @click=${this.closeImageZoom}>×</button>
2833
2841
  <img class="image-zoom-full" src=${this.zoomedImage.src} alt=${this.zoomedImage.alt} />
2834
2842
  `}
2835
2843
  </dialog>
2836
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Sy(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase===`active`}renderActivityDock(){if(this.isSendingPrompt)return this.renderActivityDockContent(`Sending your message…`,!0);let e=this.activityState();return e===void 0?null:this.renderActivityDockContent(this.activityText(e),e!==`idle`||this.activity?.phase===`active`)}renderActivityDockContent(e,t){let n=JS(this.status),r=YS(this.warningCount,this.warningsExpanded),i=n.trailing.length>0,a=this.status?Sb(this.status):``,o=i?`session-info-popover-${this.sessionId}`:void 0;return g`
2844
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Cy(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase===`active`}renderActivityDock(){if(this.isSendingPrompt)return this.renderActivityDockContent(`Sending your message…`,!0);let e=this.activityState();return e===void 0?null:this.renderActivityDockContent(this.activityText(e),e!==`idle`||this.activity?.phase===`active`)}renderActivityDockContent(e,t){let n=XS(this.status),r=ZS(this.warningCount,this.warningsExpanded),i=n.trailing.length>0,a=this.status?Cb(this.status):``,o=i?`session-info-popover-${this.sessionId}`:void 0;return g`
2837
2845
  <div class=${t?`activity-dock active`:`activity-dock`}>
2838
2846
  ${r===void 0||this.onToggleWarnings===void 0?null:g`
2839
2847
  <button
@@ -2876,20 +2884,44 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2876
2884
  `:null}
2877
2885
  ${this.renderSessionInfoPopover()}
2878
2886
  </div>
2879
- `}renderActivityMetrics(e){return e.map(e=>g`<span class=${e.className===void 0?`activity-metric`:`activity-metric ${e.className}`} title=${e.label}>${e.text}</span>`)}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return g`${IS(this.clientQueuedMessages,e).map(e=>this.renderQueuedMessageList(e))}`}renderQueuedMessageList(e){let t=GS(e,this.canClearServerQueue,this.onClearServerQueue!==void 0);return g`
2887
+ `}renderActivityMetrics(e){return e.map(e=>g`<span class=${e.className===void 0?`activity-metric`:`activity-metric ${e.className}`} title=${e.label}>${e.text}</span>`)}renderQueuedMessages(){let e=LS(this.clientQueuedMessages,this.status?.queuedMessages??[]),t=e.find(e=>e.source===`client`),n=e.filter(e=>e.source===`server`),r=n.length>0,i=KS(e,this.canClearServerQueue,this.onClearServerQueue!==void 0);return g`
2888
+ ${t===void 0?null:this.renderQueuedMessageList(t)}
2889
+ ${r||i?g`
2890
+ <div class="queued-actions">
2891
+ ${r?g`
2892
+ <button type="button" class="queued-action-button" title="Copy all queued messages" @click=${this.handleCopyAllQueuedMessages}>Copy all queues</button>
2893
+ `:null}
2894
+ ${i?g`
2895
+ <button type="button" class="queued-clear-button" title="Clear queued messages without stopping active work" @click=${this.handleClearServerQueue}>Clear all queues</button>
2896
+ `:null}
2897
+ </div>
2898
+ `:null}
2899
+ ${n.map(e=>this.renderQueuedMessageList(e))}
2900
+ `}async copyAllQueuedMessages(){await Oy(qS(LS(this.clientQueuedMessages,this.status?.queuedMessages??[]).filter(e=>e.source===`server`)))}renderQueuedMessageList(e){return g`
2880
2901
  <aside class="queued-messages" aria-live="polite">
2881
2902
  <div class="queued-header">
2882
2903
  <div class="queued-heading">
2883
2904
  <strong>${e.heading}</strong>
2884
2905
  <small>${e.detail}</small>
2885
2906
  </div>
2886
- ${t?g`
2887
- <button type="button" class="queued-clear-button" title="Clear queued messages without stopping active work" @click=${this.handleClearServerQueue}>Clear queue</button>
2888
- `:null}
2889
2907
  </div>
2890
2908
  ${e.messages.map((e,t)=>g`
2891
2909
  <div class="queued-message">
2892
- <span class="queued-kind">${e.kind===`steer`?`Steer`:`Follow-up`} ${String(t+1)}</span>
2910
+ <div class="queued-message-header">
2911
+ <span class="queued-kind">${e.kind===`steer`?`Steer`:`Follow-up`} ${String(t+1)}</span>
2912
+ <button
2913
+ type="button"
2914
+ class="queued-copy-button"
2915
+ title="Copy message"
2916
+ aria-label=${`Copy ${e.kind===`steer`?`steered`:`follow-up`} message ${String(t+1)}`}
2917
+ @click=${t=>{t.stopPropagation(),Oy(e.text)}}
2918
+ >
2919
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
2920
+ <rect x="9" y="9" width="13" height="13" rx="2" />
2921
+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
2922
+ </svg>
2923
+ </button>
2924
+ </div>
2893
2925
  <formatted-text .text=${e.text}></formatted-text>
2894
2926
  </div>
2895
2927
  `)}
@@ -2900,7 +2932,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2900
2932
  <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
2901
2933
  ${this.pendingMessageCount>0?g`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?`message`:`messages`}</small>`:null}
2902
2934
  </aside>
2903
- `:null}activityState(){let 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){let 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(){return!this.messages.length||this.messageTotal<=0?null:(this._minimapLoadedPercent=this.hasMore?PS(this.messages.length/this.conversationDisplayTotal()*100):100,g`
2935
+ `:null}activityState(){let 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){let 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(){return!this.messages.length||this.messageTotal<=0?null:(this._minimapLoadedPercent=this.hasMore?FS(this.messages.length/this.conversationDisplayTotal()*100):100,g`
2904
2936
  <chat-minimap
2905
2937
  .scrollRatio=${this._minimapViewport.scrollRatio}
2906
2938
  .viewportRatio=${this._minimapViewport.viewportRatio}
@@ -2909,7 +2941,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2909
2941
  .markers=${this._minimapMarkers}
2910
2942
  @minimap-scroll-to=${e=>{this._onMinimapScrollTo(e)}}
2911
2943
  ></chat-minimap>
2912
- `)}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;let t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart;return PS(FS(this.currentConversationIndex??t,0,e-1)/(e-1)*100)}renderHistoryBoundary(){let e=this.historyRangeLabel();return this.loadingMore?g`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?g`
2944
+ `)}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;let t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart;return FS(IS(this.currentConversationIndex??t,0,e-1)/(e-1)*100)}renderHistoryBoundary(){let e=this.historyRangeLabel();return this.loadingMore?g`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?g`
2913
2945
  <div class="history-boundary">
2914
2946
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
2915
2947
  <span>Scroll up to load earlier messages</span>
@@ -2921,7 +2953,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2921
2953
  ${n?null:this.renderMessageHeader(e,String(t))}
2922
2954
  ${e.parts.map(t=>this.renderPart(t,e))}
2923
2955
  </article>
2924
- `}renderToolImageOutput(e,t,n){let r=RS(n);return g`
2956
+ `}renderToolImageOutput(e,t,n){let r=zS(n);return g`
2925
2957
  ${this.renderScrollMarker(this.messageScrollMarkerId(t))}
2926
2958
  <article class="msg tool-image-output" data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
2927
2959
  ${this.renderMessageHeader(e,String(t),r)}
@@ -2929,10 +2961,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2929
2961
  </article>
2930
2962
  `}isToolExecutionOnlyMessage(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`toolExecution`)}renderMessageGroup(e,t,n,r){let i=this.groupDisclosureKey(t,n,r),a=this.disclosures.isOpen(i,r);return g`
2931
2963
  ${this.renderScrollMarker(this.groupScrollMarkerId(n))}
2932
- <details class=${US(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
2964
+ <details class=${WS(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
2933
2965
  <summary>
2934
- <b class="label">${WS(r)}</b>
2935
- <span>${Cy(e)}</span>
2966
+ <b class="label">${GS(r)}</b>
2967
+ <span>${wy(e)}</span>
2936
2968
  </summary>
2937
2969
  ${a?this.renderMessageGroupBody(e,t):null}
2938
2970
  </details>
@@ -2953,7 +2985,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2953
2985
  <span class=${i?`msg-meta expanded`:`msg-meta`} role="button" tabindex="0" title=${r} aria-label=${r} aria-expanded=${String(i)} @click=${()=>{this.expandedMetaKey=i?void 0:t}} @keydown=${e=>{this.onMetaKeydown(e,t,i)}}>${r}</span>
2954
2986
  </div>
2955
2987
  </div>
2956
- `}renderMessageActions(e,t){let n=this.isCopyableMessage(e),r=ZS(e,{enabled:this.canMessageActions,busy:this.messageActionsBusy()}),i=this.onEditFromHere===void 0?void 0:r.editFromHereEntryId,a=this.onForkFromHere===void 0?void 0:r.forkEntryId;if(!n&&i===void 0&&a===void 0)return null;let o=this.copiedMessageKey===t,s=a!==void 0&&this.forkingEntryId===a;return g`
2988
+ `}renderMessageActions(e,t){let n=this.isCopyableMessage(e),r=$S(e,{enabled:this.canMessageActions,busy:this.messageActionsBusy()}),i=this.onEditFromHere===void 0?void 0:r.editFromHereEntryId,a=this.onForkFromHere===void 0?void 0:r.forkEntryId;if(!n&&i===void 0&&a===void 0)return null;let o=this.copiedMessageKey===t,s=a!==void 0&&this.forkingEntryId===a;return g`
2957
2989
  <div class=${`msg-actions${s?` forking`:``}`} aria-label="Message actions">
2958
2990
  ${n?g`
2959
2991
  <button type="button" class="msg-action" title=${o?`Copied`:`Copy message`} aria-label=${`${o?`Copied`:`Copy`} ${e.role} message`} @click=${n=>{this.copyMessage(e,t,n)}}>
@@ -2961,7 +2993,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2961
2993
  </button>
2962
2994
  `:null}
2963
2995
  ${i===void 0?null:g`
2964
- <button type="button" class="msg-action msg-history-action" data-message-action="edit-from-here" title="Edit from here — branches within this session" @click=${()=>{this.editFromHere(i,QS(e))}}>
2996
+ <button type="button" class="msg-action msg-history-action" data-message-action="edit-from-here" title="Edit from here — branches within this session" @click=${()=>{this.editFromHere(i,eC(e))}}>
2965
2997
  <svg class="msg-history-action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
2966
2998
  <polyline points="15 10 20 15 15 20"></polyline>
2967
2999
  <path d="M4 4v7a4 4 0 0 0 4 4h12"></path>
@@ -2983,7 +3015,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2983
3015
  </div>
2984
3016
  `}messageActionsBusy(){return this.isSendingPrompt||this.isCompacting||this.status?.isStreaming===!0||this.status?.isBashRunning===!0||this.status?.isCompacting===!0||(this.status?.pendingMessageCount??this.pendingMessageCount)>0}async editFromHere(e,t){await this.onEditFromHere?.(e,t)}async forkFromHere(e){if(this.forkingEntryId===void 0){this.forkingEntryId=e;try{await this.onForkFromHere?.(e)}finally{this.forkingEntryId===e&&(this.forkingEntryId=void 0)}}}onMetaKeydown(e,t,n){e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),this.expandedMetaKey=n?void 0:t)}isCopyableMessage(e){return(e.role===`user`||e.role===`assistant`)&&this.messageCopyText(e)!==``}messageCopyText(e){let t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;let n=e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(e=>e!==``).join(`
2985
3017
 
2986
- `);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await Dy(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}messageMetaLabel(e){let t=this.messageMetaCache.get(e);if(t!==void 0)return t;let n=XS(e);return this.messageMetaCache.set(e,n),n}renderPart(e,t){if(e.type===`text`&&t?.role===`bash`)return g`<pre class="part shell-output">${e.text}</pre>`;if(e.type===`text`)return g`<formatted-text class="part" .text=${e.text}></formatted-text>`;if(e.type===`thinking`)return g`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
3018
+ `);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await Oy(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}messageMetaLabel(e){let t=this.messageMetaCache.get(e);if(t!==void 0)return t;let n=QS(e);return this.messageMetaCache.set(e,n),n}renderPart(e,t){if(e.type===`text`&&t?.role===`bash`)return g`<pre class="part shell-output">${e.text}</pre>`;if(e.type===`text`)return g`<formatted-text class="part" .text=${e.text}></formatted-text>`;if(e.type===`thinking`)return g`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
2987
3019
  <details class="part skill-invocation">
2988
3020
  <summary><b>[skill]</b> ${e.name}</summary>
2989
3021
  <small>${e.location}</small>
@@ -2994,58 +3026,58 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2994
3026
  <strong>Loaded ${e.name}</strong>
2995
3027
  <small>read ${e.path}</small>
2996
3028
  </div>
2997
- `;if(e.type===`image`){let{src:t,alt:n}=LS(e);return g`<img class="part chat-image" src=${t} alt=${n} loading="lazy" role="button" tabindex="0" title="Click to enlarge" @load=${this.onImageLoad} @click=${()=>{this.openImageZoom(t,n)}} @keydown=${e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.openImageZoom(t,n))}} />`}return e.type===`toolCall`?g`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type===`toolExecution`?g`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type===`toolResult`?g`
3029
+ `;if(e.type===`image`){let{src:t,alt:n}=RS(e);return g`<img class="part chat-image" src=${t} alt=${n} loading="lazy" role="button" tabindex="0" title="Click to enlarge" @load=${this.onImageLoad} @click=${()=>{this.openImageZoom(t,n)}} @keydown=${e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.openImageZoom(t,n))}} />`}return e.type===`toolCall`?g`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type===`toolExecution`?g`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type===`toolResult`?g`
2998
3030
  <details class="part" ?open=${e.isError}>
2999
3031
  <summary>${e.isError?`✖`:`✓`} ${e.toolName} result</summary>
3000
3032
  <formatted-text .text=${e.text}></formatted-text>
3001
3033
  </details>
3002
- `:null}onGroupToggle(e,t,n){let r=t.currentTarget;r instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,r.open,n)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this._updateMinimapViewport(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){let t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){let e=this.chat;if(!e)return;let t=this.didChatHeightChange(),n=this.pinnedToBottom,r=e.scrollTop<this.lastScrollTop;if(t&&n){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:r?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){let e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){let 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;let e=this.chat;e&&Uy({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(){let e=this.chat;return!e||rb(e)}isAtBottom(){let e=this.chat;return!e||nb(e)<2}canScrollUp(){let e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;let e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{let t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){let 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(()=>{let n=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,n)})}))}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;let n=this.chat;n===void 0||!this.hasMore||this.loadingMore||(n.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore}updatePinnedToBottomAfterRestore(e){e===`bottom`?this.pinnedToBottom=!0:e===`restored`&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){let e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){let e=this.chat;if(e)return Fy(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;let t=this.prependRestoreToken+1;this.prependRestoreToken=t;let n=0,r=()=>{let i=this.chat;if(!(!i||t!==this.prependRestoreToken)){if(Iy(i,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=i.scrollTop,n+=1,n<30){requestAnimationFrame(r);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};r()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){let e=this.sessionId;this.scrollController.scheduleSave(e,e=>{this.sessionId===e&&this.saveScrollPosition(e)})}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}let e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),n=Number(t?.dataset.index);if(Number.isFinite(n)){this.currentConversationIndex=FS(n,0,Math.max(0,e-1));return}this.currentConversationIndex=FS(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(){let e=this.chat;if(e!==void 0)return ob(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??ob(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,n){return n?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return zS(e)}groupRenderKey(e){return BS(e)}groupAnchorKey(e){return BS(e)}eventAnchorKey(e){return VS(e)}messageScrollMarkerId(e){return zS(e)}groupScrollMarkerId(e){return HS(e)}_updateMinimapViewport(){let e=this.chat;e&&(this._minimapViewport=lb({scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,scrollTop:e.scrollTop}),this._minimapLoadedPercent=this.hasMore?PS(this.messages.length/this.conversationDisplayTotal()*100):100)}_requestMinimapMeasure(){this._minimapMeasureTimer===void 0&&(this._minimapMeasureTimer=setTimeout(()=>{this._minimapMeasureTimer=void 0,this._measureMinimapMarkers(),this._updateMinimapViewport()},150))}_measureMinimapMarkers(){let e=this.chat;if(!e||!this.messages.length){this._minimapMarkers=[];return}let t=e.getBoundingClientRect(),n=e.scrollHeight;if(n<=0){this._minimapMarkers=[];return}let r=this.renderRoot.querySelectorAll(`article.msg.user, article.msg.assistant`),i=[];for(let a of r){let r=a.dataset.index;if(r===void 0)continue;let o=Number(r);if(!Number.isFinite(o))continue;let s=o-this.messageStart;if(s<0||s>=this.messages.length)continue;let c=this.messages[s];if(c===void 0)continue;let l=this._minimapMessagePreview(c);if(!l)continue;let u=fb(a.getBoundingClientRect().top,t.top,e.scrollTop,n);if(c.role!==`user`&&c.role!==`assistant`)continue;let d=c.role;i.push({topRatio:u,role:d,preview:l})}this._minimapMarkers=i}_minimapMessagePreview(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(e=>e!==``).join(` `).slice(0,200)}_onMinimapScrollTo(e){let t=gb(e.detail);if(t===void 0)return;let n=this.chat;if(!n)return;let r=n.scrollHeight-n.clientHeight;r<=0||(n.scrollTop=ub(t/(1-this._minimapViewport.viewportRatio))*r,this.pinnedToBottom=rb(n))}static{this.styles=pm}};B([x({attribute:!1})],K.prototype,`messages`,void 0),B([x()],K.prototype,`sessionId`,void 0),B([x({type:Number})],K.prototype,`messageStart`,void 0),B([x({type:Number})],K.prototype,`messageEnd`,void 0),B([x({type:Number})],K.prototype,`messageTotal`,void 0),B([x({type:Boolean})],K.prototype,`hasMore`,void 0),B([x({type:Boolean})],K.prototype,`loadingMore`,void 0),B([x({type:Boolean})],K.prototype,`isSendingPrompt`,void 0),B([x({type:Boolean})],K.prototype,`isCompacting`,void 0),B([x({type:Number})],K.prototype,`pendingMessageCount`,void 0),B([x({attribute:!1})],K.prototype,`clientQueuedMessages`,void 0),B([x({attribute:!1})],K.prototype,`status`,void 0),B([x({type:Number})],K.prototype,`warningCount`,void 0),B([x({type:Boolean})],K.prototype,`warningsExpanded`,void 0),B([x({attribute:!1})],K.prototype,`onToggleWarnings`,void 0),B([x({attribute:!1})],K.prototype,`activity`,void 0),B([x({attribute:!1})],K.prototype,`sessionInfo`,void 0),B([x({attribute:!1})],K.prototype,`notificationInbox`,void 0),B([x({type:Boolean})],K.prototype,`canClearServerQueue`,void 0),B([x({type:Boolean})],K.prototype,`canMessageActions`,void 0),B([x({attribute:!1})],K.prototype,`onEditFromHere`,void 0),B([x({attribute:!1})],K.prototype,`onForkFromHere`,void 0),B([x({attribute:!1})],K.prototype,`onClearServerQueue`,void 0),B([x({attribute:!1})],K.prototype,`onDismissWarning`,void 0),B([x({attribute:!1})],K.prototype,`onDismissNotification`,void 0),B([x({attribute:!1})],K.prototype,`onDismissAllNotifications`,void 0),B([x({type:Boolean})],K.prototype,`warningsVisible`,void 0),B([x({attribute:!1})],K.prototype,`onLoadMore`,void 0),B([C(`.chat`)],K.prototype,`chat`,void 0),B([C(`dialog.image-zoom`)],K.prototype,`imageZoomDialog`,void 0),B([S()],K.prototype,`pinnedToBottom`,void 0),B([S()],K.prototype,`zoomedImage`,void 0),B([S()],K.prototype,`expandedMetaKey`,void 0),B([S()],K.prototype,`copiedMessageKey`,void 0),B([S()],K.prototype,`forkingEntryId`,void 0),B([S()],K.prototype,`currentConversationIndex`,void 0),B([S()],K.prototype,`collapsedNotificationTargetKeys`,void 0),B([S()],K.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),B([S()],K.prototype,`loadMoreRequested`,void 0),B([S()],K.prototype,`sessionInfoOpen`,void 0),B([S()],K.prototype,`_minimapMarkers`,void 0),B([S()],K.prototype,`_minimapViewport`,void 0),K=B([b(`chat-view`)],K);var tC=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function nC(e){return typeof e==`string`&&tC.has(e)}function rC(e){switch(e){case`image/jpeg`:return`jpg`;case`image/png`:return`png`;case`image/gif`:return`gif`;case`image/webp`:return`webp`;default:return`bin`}}var iC=`application/octet-stream`,aC=`Failed to read an attachment.`;async function oC(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(uC(i,e))}catch{r=aC}return{attachments:n,...r===void 0?{}:{error:r}}}function sC(e){return e.kind===`image`&&nC(e.mimeType)}function cC(e){return e.every(e=>sC(e))}function lC(e,t){return cC(t)?e:`folder`}function uC(e,t){return nC(e.type)?{kind:`image`,name:fC(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:fC(e),mimeType:dC(e),data:t,size:e.size}}function dC(e){let t=e.type.trim();return t===``?iC:t}function fC(e){return e.name===``?nC(e.type)?`pasted-image.${rC(e.type)}`:`pasted-file.bin`:e.name}var pC=`pi-webui:attachment-delivery`;function mC(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function hC(e=mC()){try{return e?.getItem(pC)===`folder`?`folder`:`inline`}catch{return`inline`}}function gC(e,t=mC()){try{t?.setItem(pC,e)}catch{}}var _C=`(pointer: coarse), (max-width: 760px)`,vC=`pi-webui.promptEnterPreference`;function yC(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(_C):void 0}function bC(e){return e===`send`||e===`newline`?e:`auto`}function xC(e=EC()){if(e===void 0)return`auto`;try{return bC(e.getItem(vC))}catch{return`auto`}}function SC(e,t=EC()){if(t!==void 0)try{t.setItem(vC,e)}catch{}}function CC(e=yC(),t=xC()){return t===`send`||t!==`newline`&&e?.matches!==!0}function wC(e,t,n=yC()){return e?n?.matches!==!0||t:!1}function TC(e,t=yC(),n=xC()){let r=CC(t,n);return e?!r:r}function EC(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function DC(){return _`
3034
+ `:null}onGroupToggle(e,t,n){let r=t.currentTarget;r instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,r.open,n)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this._updateMinimapViewport(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){let t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){let e=this.chat;if(!e)return;let t=this.didChatHeightChange(),n=this.pinnedToBottom,r=e.scrollTop<this.lastScrollTop;if(t&&n){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:r?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){let e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){let 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;let e=this.chat;e&&Wy({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(){let e=this.chat;return!e||ib(e)}isAtBottom(){let e=this.chat;return!e||rb(e)<2}canScrollUp(){let e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;let e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{let t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){let 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(()=>{let n=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,n)})}))}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;let n=this.chat;n===void 0||!this.hasMore||this.loadingMore||(n.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore}updatePinnedToBottomAfterRestore(e){e===`bottom`?this.pinnedToBottom=!0:e===`restored`&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){let e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){let e=this.chat;if(e)return Iy(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;let t=this.prependRestoreToken+1;this.prependRestoreToken=t;let n=0,r=()=>{let i=this.chat;if(!(!i||t!==this.prependRestoreToken)){if(Ly(i,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=i.scrollTop,n+=1,n<30){requestAnimationFrame(r);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};r()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){let e=this.sessionId;this.scrollController.scheduleSave(e,e=>{this.sessionId===e&&this.saveScrollPosition(e)})}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}let e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),n=Number(t?.dataset.index);if(Number.isFinite(n)){this.currentConversationIndex=IS(n,0,Math.max(0,e-1));return}this.currentConversationIndex=IS(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(){let e=this.chat;if(e!==void 0)return sb(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??sb(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,n){return n?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return BS(e)}groupRenderKey(e){return VS(e)}groupAnchorKey(e){return VS(e)}eventAnchorKey(e){return HS(e)}messageScrollMarkerId(e){return BS(e)}groupScrollMarkerId(e){return US(e)}_updateMinimapViewport(){let e=this.chat;e&&(this._minimapViewport=ub({scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,scrollTop:e.scrollTop}),this._minimapLoadedPercent=this.hasMore?FS(this.messages.length/this.conversationDisplayTotal()*100):100)}_requestMinimapMeasure(){this._minimapMeasureTimer===void 0&&(this._minimapMeasureTimer=setTimeout(()=>{this._minimapMeasureTimer=void 0,this._measureMinimapMarkers(),this._updateMinimapViewport()},150))}_measureMinimapMarkers(){let e=this.chat;if(!e||!this.messages.length){this._minimapMarkers=[];return}let t=e.getBoundingClientRect(),n=e.scrollHeight;if(n<=0){this._minimapMarkers=[];return}let r=this.renderRoot.querySelectorAll(`article.msg.user, article.msg.assistant`),i=[];for(let a of r){let r=a.dataset.index;if(r===void 0)continue;let o=Number(r);if(!Number.isFinite(o))continue;let s=o-this.messageStart;if(s<0||s>=this.messages.length)continue;let c=this.messages[s];if(c===void 0)continue;let l=this._minimapMessagePreview(c);if(!l)continue;let u=pb(a.getBoundingClientRect().top,t.top,e.scrollTop,n);if(c.role!==`user`&&c.role!==`assistant`)continue;let d=c.role;i.push({topRatio:u,role:d,preview:l})}this._minimapMarkers=i}_minimapMessagePreview(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(e=>e!==``).join(` `).slice(0,200)}_onMinimapScrollTo(e){let t=_b(e.detail);if(t===void 0)return;let n=this.chat;if(!n)return;let r=n.scrollHeight-n.clientHeight;r<=0||(n.scrollTop=db(t/(1-this._minimapViewport.viewportRatio))*r,this.pinnedToBottom=ib(n))}static{this.styles=pm}};B([x({attribute:!1})],G.prototype,`messages`,void 0),B([x()],G.prototype,`sessionId`,void 0),B([x({type:Number})],G.prototype,`messageStart`,void 0),B([x({type:Number})],G.prototype,`messageEnd`,void 0),B([x({type:Number})],G.prototype,`messageTotal`,void 0),B([x({type:Boolean})],G.prototype,`hasMore`,void 0),B([x({type:Boolean})],G.prototype,`loadingMore`,void 0),B([x({type:Boolean})],G.prototype,`isSendingPrompt`,void 0),B([x({type:Boolean})],G.prototype,`isCompacting`,void 0),B([x({type:Number})],G.prototype,`pendingMessageCount`,void 0),B([x({attribute:!1})],G.prototype,`clientQueuedMessages`,void 0),B([x({attribute:!1})],G.prototype,`status`,void 0),B([x({type:Number})],G.prototype,`warningCount`,void 0),B([x({type:Boolean})],G.prototype,`warningsExpanded`,void 0),B([x({attribute:!1})],G.prototype,`onToggleWarnings`,void 0),B([x({attribute:!1})],G.prototype,`activity`,void 0),B([x({attribute:!1})],G.prototype,`sessionInfo`,void 0),B([x({attribute:!1})],G.prototype,`notificationInbox`,void 0),B([x({type:Boolean})],G.prototype,`canClearServerQueue`,void 0),B([x({type:Boolean})],G.prototype,`canMessageActions`,void 0),B([x({attribute:!1})],G.prototype,`onEditFromHere`,void 0),B([x({attribute:!1})],G.prototype,`onForkFromHere`,void 0),B([x({attribute:!1})],G.prototype,`onClearServerQueue`,void 0),B([x({attribute:!1})],G.prototype,`onDismissWarning`,void 0),B([x({attribute:!1})],G.prototype,`onDismissNotification`,void 0),B([x({attribute:!1})],G.prototype,`onDismissAllNotifications`,void 0),B([x({type:Boolean})],G.prototype,`warningsVisible`,void 0),B([x({attribute:!1})],G.prototype,`onLoadMore`,void 0),B([C(`.chat`)],G.prototype,`chat`,void 0),B([C(`dialog.image-zoom`)],G.prototype,`imageZoomDialog`,void 0),B([S()],G.prototype,`pinnedToBottom`,void 0),B([S()],G.prototype,`zoomedImage`,void 0),B([S()],G.prototype,`expandedMetaKey`,void 0),B([S()],G.prototype,`copiedMessageKey`,void 0),B([S()],G.prototype,`forkingEntryId`,void 0),B([S()],G.prototype,`currentConversationIndex`,void 0),B([S()],G.prototype,`collapsedNotificationTargetKeys`,void 0),B([S()],G.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),B([S()],G.prototype,`loadMoreRequested`,void 0),B([S()],G.prototype,`sessionInfoOpen`,void 0),B([S()],G.prototype,`_minimapMarkers`,void 0),B([S()],G.prototype,`_minimapViewport`,void 0),G=B([b(`chat-view`)],G);var rC=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function iC(e){return typeof e==`string`&&rC.has(e)}function aC(e){switch(e){case`image/jpeg`:return`jpg`;case`image/png`:return`png`;case`image/gif`:return`gif`;case`image/webp`:return`webp`;default:return`bin`}}var oC=`application/octet-stream`,sC=`Failed to read an attachment.`;async function cC(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(fC(i,e))}catch{r=sC}return{attachments:n,...r===void 0?{}:{error:r}}}function lC(e){return e.kind===`image`&&iC(e.mimeType)}function uC(e){return e.every(e=>lC(e))}function dC(e,t){return uC(t)?e:`folder`}function fC(e,t){return iC(e.type)?{kind:`image`,name:mC(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:mC(e),mimeType:pC(e),data:t,size:e.size}}function pC(e){let t=e.type.trim();return t===``?oC:t}function mC(e){return e.name===``?iC(e.type)?`pasted-image.${aC(e.type)}`:`pasted-file.bin`:e.name}var hC=`pi-webui:attachment-delivery`;function gC(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function _C(e=gC()){try{return e?.getItem(hC)===`folder`?`folder`:`inline`}catch{return`inline`}}function vC(e,t=gC()){try{t?.setItem(hC,e)}catch{}}var yC=`(pointer: coarse), (max-width: 760px)`,bC=`pi-webui.promptEnterPreference`;function xC(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(yC):void 0}function SC(e){return e===`send`||e===`newline`?e:`auto`}function CC(e=OC()){if(e===void 0)return`auto`;try{return SC(e.getItem(bC))}catch{return`auto`}}function wC(e,t=OC()){if(t!==void 0)try{t.setItem(bC,e)}catch{}}function TC(e=xC(),t=CC()){return t===`send`||t!==`newline`&&e?.matches!==!0}function EC(e,t,n=xC()){return e?n?.matches!==!0||t:!1}function DC(e,t=xC(),n=CC()){let r=TC(t,n);return e?!r:r}function OC(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function kC(){return _`
3003
3035
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3004
3036
  <path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
3005
3037
  </svg>
3006
- `}function OC(){return _`
3038
+ `}function AC(){return _`
3007
3039
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3008
3040
  <polyline points="4 14 10 14 10 20"></polyline>
3009
3041
  <polyline points="20 10 14 10 14 4"></polyline>
3010
3042
  <line x1="10" y1="14" x2="3" y2="21"></line>
3011
3043
  <line x1="21" y1="3" x2="14" y2="10"></line>
3012
3044
  </svg>
3013
- `}function kC(){return _`
3045
+ `}function jC(){return _`
3014
3046
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3015
3047
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
3016
3048
  <path d="M21 3 11.5 12.5"></path>
3017
3049
  </svg>
3018
- `}function AC(){return _`
3050
+ `}function MC(){return _`
3019
3051
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3020
3052
  <path d="M4 7h11"></path>
3021
3053
  <path d="M4 12h7"></path>
3022
3054
  <path d="M4 17h7"></path>
3023
3055
  <path d="m15 14 5 3-5 3z"></path>
3024
3056
  </svg>
3025
- `}function jC(){return kC()}function MC(){return _`
3057
+ `}function NC(){return jC()}function PC(){return _`
3026
3058
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3027
3059
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
3028
3060
  </svg>
3029
- `}function NC(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return _`
3061
+ `}function FC(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return _`
3030
3062
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3031
3063
  ${Array.from({length:t},(i,a)=>{let o=3+a*(r+n),s=4+(a+1)/t*12,c=20-s;return _`<rect class=${a<e.filled?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${o} y=${c} width=${r} height=${s} rx="1"></rect>`})}
3032
3064
  </svg>
3033
- `}var PC=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function FC(e){return e===void 0||e===``?`off`:e}function IC(e,t){let n=t.length>=2?t:PC,r=n.length-1,i=FC(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var LC=H_(class extends U_{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===V_.ELEMENT}update(e,[t,n]){if(!this.isElementPart)throw Error(`scrollWhenSelected must be used on an element`);if(t&&(!this.wasSelected||n!==this.previousKey)){let t=`element`in e?e.element:void 0;requestAnimationFrame(()=>{t instanceof HTMLElement&&t.scrollIntoView({block:`nearest`})})}this.wasSelected=t,this.previousKey=n}render(e,t){}}),RC=class extends y{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
3065
+ `}var IC=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function LC(e){return e===void 0||e===``?`off`:e}function RC(e,t){let n=t.length>=2?t:IC,r=n.length-1,i=LC(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var zC=H_(class extends U_{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===V_.ELEMENT}update(e,[t,n]){if(!this.isElementPart)throw Error(`scrollWhenSelected must be used on an element`);if(t&&(!this.wasSelected||n!==this.previousKey)){let t=`element`in e?e.element:void 0;requestAnimationFrame(()=>{t instanceof HTMLElement&&t.scrollIntoView({block:`nearest`})})}this.wasSelected=t,this.previousKey=n}render(e,t){}}),BC=class extends y{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
3034
3066
  <div class="menu">
3035
3067
  ${this.items.map((e,t)=>g`
3036
- <button class=${t===this.selectedIndex?`selected`:``} ${LC(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
3068
+ <button class=${t===this.selectedIndex?`selected`:``} ${zC(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
3037
3069
  <strong>${e.insertText}</strong>
3038
3070
  <span>${e.detail}</span>
3039
3071
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
3040
3072
  </button>
3041
3073
  `)}
3042
3074
  </div>
3043
- `:null}static{this.styles=hm}};B([x({attribute:!1})],RC.prototype,`items`,void 0),B([x({type:Number})],RC.prototype,`selectedIndex`,void 0),B([x({attribute:!1})],RC.prototype,`onPick`,void 0),RC=B([b(`autocomplete-menu`)],RC);var q=class extends y{constructor(...e){super(...e),this.disabled=!1,this.machineId=`local`,this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.showSessionConfiguration=!1,this.availableThinkingLevels=[],this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=hC(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=yC(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=BC(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&$c(n,this.draft);let r=BC(this.machineId,this.sessionId);this.draft=r===void 0?``:Qc(r),this.currentInputMode=su(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!zC(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){let e=this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.disabled||this.sending,i=r||this.canSteer||this.isCompacting||this.canStop;return g`
3075
+ `:null}static{this.styles=hm}};B([x({attribute:!1})],BC.prototype,`items`,void 0),B([x({type:Number})],BC.prototype,`selectedIndex`,void 0),B([x({attribute:!1})],BC.prototype,`onPick`,void 0),BC=B([b(`autocomplete-menu`)],BC);var K=class extends y{constructor(...e){super(...e),this.disabled=!1,this.machineId=`local`,this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.showSessionConfiguration=!1,this.availableThinkingLevels=[],this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=_C(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=xC(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=HC(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&$c(n,this.draft);let r=HC(this.machineId,this.sessionId);this.draft=r===void 0?``:Qc(r),this.currentInputMode=su(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!VC(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){let e=this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.disabled||this.sending,i=r||this.canSteer||this.isCompacting||this.canStop;return g`
3044
3076
  <footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
3045
3077
  <div class="editor-wrap">
3046
3078
  <div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="Message pi" aria-disabled=${this.disabled?`true`:`false`}></div>
3047
3079
  <input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
3048
- <button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${DC()}</button>
3080
+ <button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${kC()}</button>
3049
3081
  ${t?g`<div class="mode-hint">Shell command${e.excludeFromContext?` · excluded from context`:``}</div>`:null}
3050
3082
  ${this.isCompacting&&!t?g`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
3051
3083
  ${this.renderAttachments()}
@@ -3053,21 +3085,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3053
3085
  </div>
3054
3086
  <div class="actions">
3055
3087
  ${this.renderCompactStatus()}
3056
- ${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${i} title="Compact context" aria-label="Compact context" @click=${()=>this.onCompact?.()}>${OC()}<span>Compact</span></button>`}
3057
- <button class="icon-button send-button" ?disabled=${r} title=${n?`Queue until the current activity finishes`:`Send message`} aria-label=${n?`Queue message`:`Send message`} @click=${()=>{this.send(`followUp`)}}>${n?AC():kC()}</button>
3058
- ${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${r} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send(`steer`)}}>${jC()}</button>`:null}
3059
- <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`Stop current work and clear queued messages`:`Nothing running`} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${MC()}</button>
3088
+ ${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${i} title="Compact context" aria-label="Compact context" @click=${()=>this.onCompact?.()}>${AC()}<span>Compact</span></button>`}
3089
+ <button class="icon-button send-button" ?disabled=${r} title=${n?`Queue until the current activity finishes`:`Send message`} aria-label=${n?`Queue message`:`Send message`} @click=${()=>{this.send(`followUp`)}}>${n?MC():jC()}</button>
3090
+ ${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${r} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send(`steer`)}}>${NC()}</button>`:null}
3091
+ <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`Stop current work and clear queued messages`:`Nothing running`} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${PC()}</button>
3060
3092
  </div>
3061
3093
  </footer>
3062
- `}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=BC(this.machineId,this.sessionId);t!==void 0&&$c(t,e);let n=this.editor;if(n!==void 0){let t=n.state.doc.toString();n.dispatch({...t===e?{}:{changes:{from:0,to:t.length,insert:e}},selection:i.cursor(e.length)})}this.requestVersion+=1,this.currentInputMode=su(e),this.completions=[],this.selectedIndex=0}get view(){return this.editor}renderCompactStatus(){let e=this.status===void 0&&this.showSessionConfiguration,t=this.status??(e?this.sessionConfiguration:void 0);if(t===void 0&&!e)return null;let n=t?.model?.id??(e?`Choose default model`:`no model`),r=t?.model?.provider!==void 0&&t.model.provider!==``?`${t.model.provider}/`:``,i=e?`Default thinking level: ${FC(t?.thinkingLevel)}`:`Thinking level: ${FC(t?.thinkingLevel)}`;return g`
3094
+ `}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=HC(this.machineId,this.sessionId);t!==void 0&&$c(t,e);let n=this.editor;if(n!==void 0){let t=n.state.doc.toString();n.dispatch({...t===e?{}:{changes:{from:0,to:t.length,insert:e}},selection:i.cursor(e.length)})}this.requestVersion+=1,this.currentInputMode=su(e),this.completions=[],this.selectedIndex=0}get view(){return this.editor}renderCompactStatus(){let e=this.status===void 0&&this.showSessionConfiguration,t=this.status??(e?this.sessionConfiguration:void 0);if(t===void 0&&!e)return null;let n=t?.model?.id??(e?`Choose default model`:`no model`),r=t?.model?.provider!==void 0&&t.model.provider!==``?`${t.model.provider}/`:``,i=e?`Default thinking level: ${LC(t?.thinkingLevel)}`:`Thinking level: ${LC(t?.thinkingLevel)}`;return g`
3063
3095
  <div class="compact-status" aria-label=${e?`Session defaults`:`Session status`}>
3064
3096
  <button class="select-model" ?disabled=${this.onSelectModel===void 0} title="Select model" @click=${()=>this.onSelectModel?.()}>${r}${n}</button>
3065
- <button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0} title=${i} aria-label=${i} @click=${()=>this.onSelectThinking?.()}>${NC(IC(t?.thinkingLevel,this.availableThinkingLevels))}</button>
3097
+ <button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0} title=${i} aria-label=${i} @click=${()=>this.onSelectThinking?.()}>${FC(RC(t?.thinkingLevel,this.availableThinkingLevels))}</button>
3066
3098
  </div>
3067
- `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=cC(this.attachments),t=this.effectiveAttachmentDelivery();return g`
3099
+ `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=uC(this.attachments),t=this.effectiveAttachmentDelivery();return g`
3068
3100
  <div class="attachments" aria-label="Pending attachments">
3069
3101
  ${this.attachments.map(e=>g`
3070
- <div class=${`attachment-chip ${sC(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
3102
+ <div class=${`attachment-chip ${lC(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
3071
3103
  ${this.renderAttachmentPreview(e)}
3072
3104
  <button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
3073
3105
  </div>
@@ -3082,10 +3114,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3082
3114
  `:null}
3083
3115
  ${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
3084
3116
  </div>
3085
- `}renderAttachmentPreview(e){return sC(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
3086
- <div class="attachment-file-preview" aria-hidden="true">${KC(e.name)}</div>
3117
+ `}renderAttachmentPreview(e){return lC(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
3118
+ <div class="attachment-file-preview" aria-hidden="true">${JC(e.name)}</div>
3087
3119
  <span class="attachment-file-name">${e.name}</span>
3088
- `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!cC(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,gC(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){let t=UC(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&WC(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=UC(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;let{attachments:t,error:n}=await oC(e,qC);t.length>0&&(this.attachments=[...this.attachments,...t.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))]),n!==void 0&&(this.attachmentError=n)}currentAttachments(){return this.attachments.map(e=>GC(e))}effectiveAttachmentDelivery(){return lC(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new p({parent:this.editorHost,state:e.create({doc:this.draft,extensions:[m(),ne(),t(),u.of(` `),r(a,{fallback:!0}),p.lineWrapping,p.contentAttributes.of(e=>XC(e.state.sliceDoc(0,e.state.selection.main.head))),p.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),o(`Message pi... Use / for commands, @ for tracked files, @ space for all files`),this.editableCompartment.of(p.editable.of(!this.disabled)),this.readOnlyCompartment.of(e.readOnly.of(this.disabled)),p.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),n.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>l.shift?.(e)??!1},{key:`Backspace`,run:e=>ee(e)},...c,...d])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:i.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(p.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(e.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=BC(this.machineId,this.sessionId);t!==void 0&&$c(t,this.draft);let n=su(this.draft);lu(n,this.currentInputMode)||(this.currentInputMode=n),this.refreshCompletions()}async refreshCompletions(){let 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!==``){let n=await L.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(VC);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:t.source,...t.description===void 0?{}:{description:t.description}}))}else if(e.kind===`file`&&this.cwd!==void 0&&this.cwd!==``){let n=await L.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(HC);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=nu(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}}currentTrigger(){return tu(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=wC(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,n)}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return TC(t,this.mobilePromptEnterMedia,xC())?(this.send(this.canSteer||this.isCompacting?`followUp`:void 0),!0):te(e)||f(e)}handleEditorTab(e){if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):l.run?.(e)??!1}pick(e){let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,a=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:a,insert:`${e.insertText}${n}`},selection:i.cursor(r),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;let t=this.draft.trim(),n=this.attachments;if(t===``&&n.length===0)return;let r=this.canSteer||this.isCompacting?e:void 0,i=n.length>0?this.currentAttachments():void 0,a=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=BC(this.machineId,this.sessionId);e!==void 0&&el(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=vm}};B([x({type:Boolean})],q.prototype,`disabled`,void 0),B([x()],q.prototype,`sessionId`,void 0),B([x()],q.prototype,`cwd`,void 0),B([x()],q.prototype,`machineId`,void 0),B([x()],q.prototype,`projectId`,void 0),B([x()],q.prototype,`workspaceId`,void 0),B([x({type:Boolean})],q.prototype,`workspaceScopedFileSuggestions`,void 0),B([x({type:Boolean})],q.prototype,`canSteer`,void 0),B([x({type:Boolean})],q.prototype,`isCompacting`,void 0),B([x({type:Boolean})],q.prototype,`canStop`,void 0),B([x({attribute:!1})],q.prototype,`status`,void 0),B([x({type:Boolean})],q.prototype,`sending`,void 0),B([x({attribute:!1})],q.prototype,`onSend`,void 0),B([x({attribute:!1})],q.prototype,`onStop`,void 0),B([x({attribute:!1})],q.prototype,`onSelectModel`,void 0),B([x({attribute:!1})],q.prototype,`onSelectThinking`,void 0),B([x({attribute:!1})],q.prototype,`onCompact`,void 0),B([x({type:Boolean})],q.prototype,`showSessionConfiguration`,void 0),B([x({attribute:!1})],q.prototype,`sessionConfiguration`,void 0),B([x({attribute:!1})],q.prototype,`availableThinkingLevels`,void 0),B([C(`.markdown-editor`)],q.prototype,`editorHost`,void 0),B([C(`.attachment-input`)],q.prototype,`attachmentInput`,void 0),B([S()],q.prototype,`currentInputMode`,void 0),B([S()],q.prototype,`completions`,void 0),B([S()],q.prototype,`selectedIndex`,void 0),B([S()],q.prototype,`attachments`,void 0),B([S()],q.prototype,`attachmentDelivery`,void 0),B([S()],q.prototype,`attachmentError`,void 0),q=B([b(`prompt-editor`)],q);function zC(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function BC(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Jo(e,t)}function VC(){return[]}function HC(){return[]}function UC(e){return e===null?[]:Array.from(e.files)}function WC(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function GC(e){return e.kind===`image`?{kind:`image`,mimeType:e.mimeType,data:e.data,name:e.name}:{kind:`file`,mimeType:e.mimeType,data:e.data,name:e.name}}function KC(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function qC(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(`Failed to read file`))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(`Unexpected file reader result`));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var JC={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},YC={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function XC(e){return su(e).kind===`normal`?JC:YC}var ZC=class extends y{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
3120
+ `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!uC(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,vC(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){let t=GC(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&KC(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=GC(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;let{attachments:t,error:n}=await cC(e,YC);t.length>0&&(this.attachments=[...this.attachments,...t.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))]),n!==void 0&&(this.attachmentError=n)}currentAttachments(){return this.attachments.map(e=>qC(e))}effectiveAttachmentDelivery(){return dC(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new p({parent:this.editorHost,state:e.create({doc:this.draft,extensions:[m(),ne(),t(),u.of(` `),r(a,{fallback:!0}),p.lineWrapping,p.contentAttributes.of(e=>QC(e.state.sliceDoc(0,e.state.selection.main.head))),p.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),o(`Message pi... Use / for commands, @ for tracked files, @ space for all files`),this.editableCompartment.of(p.editable.of(!this.disabled)),this.readOnlyCompartment.of(e.readOnly.of(this.disabled)),p.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),n.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>l.shift?.(e)??!1},{key:`Backspace`,run:e=>ee(e)},...c,...d])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:i.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(p.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(e.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=HC(this.machineId,this.sessionId);t!==void 0&&$c(t,this.draft);let n=su(this.draft);lu(n,this.currentInputMode)||(this.currentInputMode=n),this.refreshCompletions()}async refreshCompletions(){let 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!==``){let n=await L.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(UC);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:t.source,...t.description===void 0?{}:{description:t.description}}))}else if(e.kind===`file`&&this.cwd!==void 0&&this.cwd!==``){let n=await L.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(WC);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=nu(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}}currentTrigger(){return tu(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=EC(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,n)}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return DC(t,this.mobilePromptEnterMedia,CC())?(this.send(this.canSteer||this.isCompacting?`followUp`:void 0),!0):te(e)||f(e)}handleEditorTab(e){if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):l.run?.(e)??!1}pick(e){let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,a=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:a,insert:`${e.insertText}${n}`},selection:i.cursor(r),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;let t=this.draft.trim(),n=this.attachments;if(t===``&&n.length===0)return;let r=this.canSteer||this.isCompacting?e:void 0,i=n.length>0?this.currentAttachments():void 0,a=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=HC(this.machineId,this.sessionId);e!==void 0&&el(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=vm}};B([x({type:Boolean})],K.prototype,`disabled`,void 0),B([x()],K.prototype,`sessionId`,void 0),B([x()],K.prototype,`cwd`,void 0),B([x()],K.prototype,`machineId`,void 0),B([x()],K.prototype,`projectId`,void 0),B([x()],K.prototype,`workspaceId`,void 0),B([x({type:Boolean})],K.prototype,`workspaceScopedFileSuggestions`,void 0),B([x({type:Boolean})],K.prototype,`canSteer`,void 0),B([x({type:Boolean})],K.prototype,`isCompacting`,void 0),B([x({type:Boolean})],K.prototype,`canStop`,void 0),B([x({attribute:!1})],K.prototype,`status`,void 0),B([x({type:Boolean})],K.prototype,`sending`,void 0),B([x({attribute:!1})],K.prototype,`onSend`,void 0),B([x({attribute:!1})],K.prototype,`onStop`,void 0),B([x({attribute:!1})],K.prototype,`onSelectModel`,void 0),B([x({attribute:!1})],K.prototype,`onSelectThinking`,void 0),B([x({attribute:!1})],K.prototype,`onCompact`,void 0),B([x({type:Boolean})],K.prototype,`showSessionConfiguration`,void 0),B([x({attribute:!1})],K.prototype,`sessionConfiguration`,void 0),B([x({attribute:!1})],K.prototype,`availableThinkingLevels`,void 0),B([C(`.markdown-editor`)],K.prototype,`editorHost`,void 0),B([C(`.attachment-input`)],K.prototype,`attachmentInput`,void 0),B([S()],K.prototype,`currentInputMode`,void 0),B([S()],K.prototype,`completions`,void 0),B([S()],K.prototype,`selectedIndex`,void 0),B([S()],K.prototype,`attachments`,void 0),B([S()],K.prototype,`attachmentDelivery`,void 0),B([S()],K.prototype,`attachmentError`,void 0),K=B([b(`prompt-editor`)],K);function VC(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function HC(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Jo(e,t)}function UC(){return[]}function WC(){return[]}function GC(e){return e===null?[]:Array.from(e.files)}function KC(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function qC(e){return e.kind===`image`?{kind:`image`,mimeType:e.mimeType,data:e.data,name:e.name}:{kind:`file`,mimeType:e.mimeType,data:e.data,name:e.name}}function JC(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function YC(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(`Failed to read file`))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(`Unexpected file reader result`));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var XC={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},ZC={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function QC(e){return su(e).kind===`normal`?XC:ZC}var $C=class extends y{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
3089
3121
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
3090
3122
  <section @mousedown=${e=>{e.stopPropagation()}}>
3091
3123
  <header>
@@ -3101,12 +3133,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3101
3133
  `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?`input`:`.options`)?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){let e=this.query.trim().toLowerCase();return e===``?this.options:this.options.filter(t=>`${t.label} ${t.description??``} ${t.value}`.toLowerCase().includes(e))}renderGroupedOptions(e){let t=[];for(let[n,r]of e.entries()){let e=t[t.length-1];e!==void 0&&e.group===r.group?e.items.push({option:r,index:n}):t.push({group:r.group,items:[{option:r,index:n}]})}return t.map(e=>{let t=e.group!==void 0&&e.group!==``;return g`
3102
3134
  ${t?g`<div class="group-header">${e.group}</div>`:null}
3103
3135
  ${e.items.map(({option:e,index:n})=>g`
3104
- <button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${LC(n===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
3136
+ <button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${zC(n===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
3105
3137
  <span>${e.label}</span>
3106
3138
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
3107
3139
  </button>
3108
3140
  `)}
3109
- `})}handleKeyDown(e){let 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();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=gm}};B([x()],ZC.prototype,`title`,void 0),B([x({type:Boolean})],ZC.prototype,`searchable`,void 0),B([x({attribute:!1})],ZC.prototype,`options`,void 0),B([x({attribute:!1})],ZC.prototype,`selectedValue`,void 0),B([x({attribute:!1})],ZC.prototype,`onPick`,void 0),B([x({attribute:!1})],ZC.prototype,`onCancel`,void 0),B([S()],ZC.prototype,`selectedIndex`,void 0),B([S()],ZC.prototype,`query`,void 0),ZC=B([b(`command-picker`)],ZC);var QC=class extends y{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
3141
+ `})}handleKeyDown(e){let 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();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=gm}};B([x()],$C.prototype,`title`,void 0),B([x({type:Boolean})],$C.prototype,`searchable`,void 0),B([x({attribute:!1})],$C.prototype,`options`,void 0),B([x({attribute:!1})],$C.prototype,`selectedValue`,void 0),B([x({attribute:!1})],$C.prototype,`onPick`,void 0),B([x({attribute:!1})],$C.prototype,`onCancel`,void 0),B([S()],$C.prototype,`selectedIndex`,void 0),B([S()],$C.prototype,`query`,void 0),$C=B([b(`command-picker`)],$C);var ew=class extends y{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
3110
3142
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
3111
3143
  <section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3112
3144
  <header>
@@ -3119,7 +3151,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3119
3151
  </header>
3120
3152
  <div class="options">
3121
3153
  ${e.length===0?g`<div class="empty">No actions found.</div>`:e.map((e,t)=>g`
3122
- <button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${LC(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
3154
+ <button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${zC(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
3123
3155
  <span class="main">
3124
3156
  <strong>${e.title}</strong>
3125
3157
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
@@ -3132,7 +3164,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3132
3164
  </div>
3133
3165
  </section>
3134
3166
  </div>
3135
- `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return $C(this.actions,this.queryText)}handleKeyDown(e){let 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();let n=t[this.selectedIndex];n!==void 0&&this.run(n)}}run(e){e.enabled!==!1&&this.onRun?.(e)}static{this.styles=_m}};B([x({attribute:!1})],QC.prototype,`actions`,void 0),B([x({attribute:!1})],QC.prototype,`onRun`,void 0),B([x({attribute:!1})],QC.prototype,`onCancel`,void 0),B([C(`input`)],QC.prototype,`input`,void 0),B([S()],QC.prototype,`queryText`,void 0),B([S()],QC.prototype,`selectedIndex`,void 0),QC=B([b(`action-palette`)],QC);function $C(e,t){let n=t.trim().toLowerCase();return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||[e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `).toLowerCase().includes(n))}var ew=class extends y{render(){let e=this.state;return e===void 0?null:g`
3167
+ `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return tw(this.actions,this.queryText)}handleKeyDown(e){let 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();let n=t[this.selectedIndex];n!==void 0&&this.run(n)}}run(e){e.enabled!==!1&&this.onRun?.(e)}static{this.styles=_m}};B([x({attribute:!1})],ew.prototype,`actions`,void 0),B([x({attribute:!1})],ew.prototype,`onRun`,void 0),B([x({attribute:!1})],ew.prototype,`onCancel`,void 0),B([C(`input`)],ew.prototype,`input`,void 0),B([S()],ew.prototype,`queryText`,void 0),B([S()],ew.prototype,`selectedIndex`,void 0),ew=B([b(`action-palette`)],ew);function tw(e,t){let n=t.trim().toLowerCase();return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||[e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `).toLowerCase().includes(n))}var nw=class extends y{render(){let e=this.state;return e===void 0?null:g`
3136
3168
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
3137
3169
  <section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3138
3170
  <header>
@@ -3155,13 +3187,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3155
3187
  <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>
3156
3188
  </div>
3157
3189
  `;case`oauth`:return this.renderOAuth(e);case`logout`:return g`<div class="options">${e.providers.length===0?g`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(e=>g`
3158
- <button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${nw(e.authType)}</small></button>
3190
+ <button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${iw(e.authType)}</small></button>
3159
3191
  `)}</div>`}}renderProviderButton(e){return g`
3160
3192
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
3161
- <span>${e.name}${e.status.source===void 0?null:g` <em>${iw(e)}</em>`}</span>
3162
- <small>${e.id} · ${nw(e.authType)}</small>
3193
+ <span>${e.name}${e.status.source===void 0?null:g` <em>${ow(e)}</em>`}</span>
3194
+ <small>${e.id} · ${iw(e.authType)}</small>
3163
3195
  </button>
3164
- `}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=tw(n?.promptType);return g`
3196
+ `}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=rw(n?.promptType);return g`
3165
3197
  <div class="form">
3166
3198
  ${t.auth===void 0?g`<p>Starting login flow…</p>`:g`
3167
3199
  <p>Open this authorization link:</p>
@@ -3194,7 +3226,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3194
3226
  ${t.status===`error`||t.status===`cancelled`?g`<div class="error-text">${t.error??t.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
3195
3227
  ${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
3196
3228
  </div>
3197
- `}focusInputIfNeeded(){let e=rw(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;let 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?.()}static{this.styles=[gm,h`
3229
+ `}focusInputIfNeeded(){let e=aw(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;let 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?.()}static{this.styles=[gm,h`
3198
3230
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
3199
3231
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
3200
3232
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -3212,7 +3244,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3212
3244
  .inline-options button { display: grid; gap: 2px; text-align: left; }
3213
3245
  .inline-options small { color: var(--pi-muted); }
3214
3246
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
3215
- `]}};B([x({attribute:!1})],ew.prototype,`state`,void 0),B([x({attribute:!1})],ew.prototype,`onChooseMethod`,void 0),B([x({attribute:!1})],ew.prototype,`onSelectProvider`,void 0),B([x({attribute:!1})],ew.prototype,`onApiKeyInput`,void 0),B([x({attribute:!1})],ew.prototype,`onSaveApiKey`,void 0),B([x({attribute:!1})],ew.prototype,`onLogoutProvider`,void 0),B([x({attribute:!1})],ew.prototype,`onOAuthInput`,void 0),B([x({attribute:!1})],ew.prototype,`onOAuthRespond`,void 0),B([x({attribute:!1})],ew.prototype,`onOAuthCancel`,void 0),B([x({attribute:!1})],ew.prototype,`onCancel`,void 0),B([C(`input`)],ew.prototype,`input`,void 0),ew=B([b(`auth-dialog`)],ew);function tw(e){return e===`secret`?`password`:`text`}function nw(e){return e===`oauth`?`subscription`:`credentials`}function rw(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 iw(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 aw=[`openai-completions`,`openai-responses`,`anthropic-messages`,`google-generative-ai`];function ow(e){return aw.map(t=>({api:t,selected:t===e}))}function sw(e,t){return e.map(e=>({candidate:e,selected:e.id===t}))}var cw=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function lw(e){let t=e.providers??{},n=bw(t);return{config:_w(e,{...t,[n]:{api:`openai-completions`}}),providerName:n}}function uw(e,t,n){let r=n.trim(),i=e.providers??{};if(r===``)return{config:e,error:`Provider name is required.`};if(t===r)return{config:e};if(i[t]===void 0)return{config:e,error:`Provider "${t}" no longer exists.`};if(i[r]!==void 0)return{config:e,error:`A provider named "${r}" already exists.`};let a={};for(let[e,n]of Object.entries(i))a[e===t?r:e]=n;return{config:_w(e,a)}}function dw(e,t,n){let r=e.providers??{};return r[t]===void 0?e:_w(e,{...r,[t]:n})}function fw(e,t){let n=e.providers??{};return n[t]===void 0?e:_w(e,vw(n,t))}function pw(e,t){let n=e.providers?.[t];if(n===void 0)return e;let r=[...n.models??[],{id:``}];return dw(e,t,{...n,models:r})}function mw(e,t,n,r){let i=e.providers?.[t],a=i?.models;if(i===void 0||a===void 0||n<0||n>=a.length)return e;let o=[...a];return o[n]=r,dw(e,t,{...i,models:o})}function hw(e,t,n){let r=e.providers?.[t],i=r?.models;if(r===void 0||i===void 0||n<0||n>=i.length)return e;let a=i.filter((e,t)=>t!==n);if(a.length===0){let n={...r};return delete n.models,dw(e,t,n)}return dw(e,t,{...r,models:a})}function gw(e,t,n,r){let i=n==="default"?yw(e??{},t):{...e??{}};if(n===`disabled`&&(i[t]=null),n===`custom`){let e=r?.trim();i[t]=e===void 0||e===``?t:e}return Object.keys(i).length===0?void 0:i}function _w(e,t){return{...e,providers:t}}function vw(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function yw(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function bw(e){let t=`new-provider`,n=1;for(;e[t]!==void 0;)t=`new-provider-${String(n++)}`;return t}var xw={thinkingFormat:`deepseek`,requiresReasoningContentOnAssistantMessages:!0},Sw=class extends y{constructor(...e){super(...e),this.modelsApi=Xa,this.config={providers:{}},this.loading=!0,this.saving=!1,this.error=``,this.savedMessage=``,this.providerNameDraft=``,this.renameError=``,this.advancedErrors={},this.modelTests={},this.discoveredModels={},this.loadRequestSequence=0,this.modelDiscoverySequence=0,this.modelDiscoveryRequestSequences=new Map}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){e.has(`machine`)&&Tw(e.get(`machine`))!==this.machineId()&&(this.resetForMachineChange(),this.isConnected&&this.loadConfig())}render(){return g`
3247
+ `]}};B([x({attribute:!1})],nw.prototype,`state`,void 0),B([x({attribute:!1})],nw.prototype,`onChooseMethod`,void 0),B([x({attribute:!1})],nw.prototype,`onSelectProvider`,void 0),B([x({attribute:!1})],nw.prototype,`onApiKeyInput`,void 0),B([x({attribute:!1})],nw.prototype,`onSaveApiKey`,void 0),B([x({attribute:!1})],nw.prototype,`onLogoutProvider`,void 0),B([x({attribute:!1})],nw.prototype,`onOAuthInput`,void 0),B([x({attribute:!1})],nw.prototype,`onOAuthRespond`,void 0),B([x({attribute:!1})],nw.prototype,`onOAuthCancel`,void 0),B([x({attribute:!1})],nw.prototype,`onCancel`,void 0),B([C(`input`)],nw.prototype,`input`,void 0),nw=B([b(`auth-dialog`)],nw);function rw(e){return e===`secret`?`password`:`text`}function iw(e){return e===`oauth`?`subscription`:`credentials`}function aw(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 ow(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 sw=[`openai-completions`,`openai-responses`,`anthropic-messages`,`google-generative-ai`];function cw(e){return sw.map(t=>({api:t,selected:t===e}))}function lw(e,t){return e.map(e=>({candidate:e,selected:e.id===t}))}var uw=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function dw(e){let t=e.providers??{},n=Sw(t);return{config:yw(e,{...t,[n]:{api:`openai-completions`}}),providerName:n}}function fw(e,t,n){let r=n.trim(),i=e.providers??{};if(r===``)return{config:e,error:`Provider name is required.`};if(t===r)return{config:e};if(i[t]===void 0)return{config:e,error:`Provider "${t}" no longer exists.`};if(i[r]!==void 0)return{config:e,error:`A provider named "${r}" already exists.`};let a={};for(let[e,n]of Object.entries(i))a[e===t?r:e]=n;return{config:yw(e,a)}}function pw(e,t,n){let r=e.providers??{};return r[t]===void 0?e:yw(e,{...r,[t]:n})}function mw(e,t){let n=e.providers??{};return n[t]===void 0?e:yw(e,bw(n,t))}function hw(e,t){let n=e.providers?.[t];if(n===void 0)return e;let r=[...n.models??[],{id:``}];return pw(e,t,{...n,models:r})}function gw(e,t,n,r){let i=e.providers?.[t],a=i?.models;if(i===void 0||a===void 0||n<0||n>=a.length)return e;let o=[...a];return o[n]=r,pw(e,t,{...i,models:o})}function _w(e,t,n){let r=e.providers?.[t],i=r?.models;if(r===void 0||i===void 0||n<0||n>=i.length)return e;let a=i.filter((e,t)=>t!==n);if(a.length===0){let n={...r};return delete n.models,pw(e,t,n)}return pw(e,t,{...r,models:a})}function vw(e,t,n,r){let i=n==="default"?xw(e??{},t):{...e??{}};if(n===`disabled`&&(i[t]=null),n===`custom`){let e=r?.trim();i[t]=e===void 0||e===``?t:e}return Object.keys(i).length===0?void 0:i}function yw(e,t){return{...e,providers:t}}function bw(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function xw(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function Sw(e){let t=`new-provider`,n=1;for(;e[t]!==void 0;)t=`new-provider-${String(n++)}`;return t}var Cw={thinkingFormat:`deepseek`,requiresReasoningContentOnAssistantMessages:!0},ww=class extends y{constructor(...e){super(...e),this.modelsApi=Xa,this.config={providers:{}},this.loading=!0,this.saving=!1,this.error=``,this.savedMessage=``,this.providerNameDraft=``,this.renameError=``,this.advancedErrors={},this.modelTests={},this.discoveredModels={},this.loadRequestSequence=0,this.modelDiscoverySequence=0,this.modelDiscoveryRequestSequences=new Map}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){e.has(`machine`)&&Dw(e.get(`machine`))!==this.machineId()&&(this.resetForMachineChange(),this.isConnected&&this.loadConfig())}render(){return g`
3216
3248
  <div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
3217
3249
  <section class="dialog" role="dialog" aria-modal="true" aria-labelledby="models-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3218
3250
  <header>
@@ -3223,10 +3255,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3223
3255
  </div>
3224
3256
  <div class="header-actions">
3225
3257
  <button class="icon-button" type="button" title="Reload models configuration" aria-label="Reload models configuration" ?disabled=${this.loading} @click=${()=>{this.loadConfig()}}>
3226
- ${$w()}
3258
+ ${tT()}
3227
3259
  </button>
3228
3260
  <button class="icon-button" type="button" title="Close models configuration" aria-label="Close models configuration" @click=${()=>{this.close()}}>
3229
- ${eT()}
3261
+ ${nT()}
3230
3262
  </button>
3231
3263
  </div>
3232
3264
  </header>
@@ -3244,7 +3276,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3244
3276
  ${this.savedMessage===``?null:g`<span class="saved-message">${this.savedMessage}</span>`}
3245
3277
  </div>
3246
3278
  <button type="button" class="secondary" @click=${()=>{this.configureAuth()}}>
3247
- ${tT()} Authentication
3279
+ ${rT()} Authentication
3248
3280
  </button>
3249
3281
  <button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
3250
3282
  <button type="button" class="primary" ?disabled=${this.saving||this.loading} @click=${()=>{this.saveConfig()}}>
@@ -3265,28 +3297,28 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3265
3297
  </div>
3266
3298
  <div class="tree-actions">
3267
3299
  <button type="button" class="add-provider" @click=${()=>{this.addCustomProvider()}}>
3268
- ${Zw()} Add provider
3300
+ ${$w()} Add provider
3269
3301
  </button>
3270
3302
  <button type="button" class="auth-link" @click=${()=>{this.configureAuth()}}>
3271
- ${tT()} Configure authentication
3303
+ ${rT()} Configure authentication
3272
3304
  </button>
3273
3305
  </div>
3274
3306
  </aside>
3275
3307
  `}renderProviderTreeNode(e,t){let n=this.selection?.type===`provider`&&this.selection.providerName===e,r=t.models??[];return g`
3276
3308
  <div class="provider-node">
3277
3309
  <button class="tree-row provider-row ${n?`selected`:``}" type="button" @click=${()=>{this.selectProvider(e)}}>
3278
- ${Yw()}
3310
+ ${Zw()}
3279
3311
  <span class="tree-label">${e}</span>
3280
3312
  </button>
3281
3313
  ${r.map((t,n)=>g`
3282
3314
  <button class="tree-row model-row ${this.selection?.type===`model`&&this.selection.providerName===e&&this.selection.index===n?`selected`:``}" type="button" @click=${()=>{this.selectModel(e,n)}}>
3283
- ${Xw()}
3315
+ ${Qw()}
3284
3316
  <span class="tree-label">${t.id.trim()===``?`new model`:t.id}</span>
3285
3317
  ${t.reasoning===!0?g`<span class="thinking-mark" title="Reasoning enabled">T</span>`:null}
3286
3318
  </button>
3287
3319
  `)}
3288
3320
  <button class="tree-row add-model" type="button" @click=${()=>{this.addModel(e)}}>
3289
- ${Zw()} <span>Add model</span>
3321
+ ${$w()} <span>Add model</span>
3290
3322
  </button>
3291
3323
  </div>
3292
3324
  `}renderDetail(){let e=this.selection;if(e===void 0)return g`
@@ -3303,16 +3335,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3303
3335
  </div>
3304
3336
  <div class="provider-actions">
3305
3337
  <button type="button" class="secondary" ?disabled=${!r||n?.phase===`discovering`} @click=${()=>{this.discoverModels(e)}}>
3306
- ${n?.phase===`discovering`?rT():$w()} ${n===void 0?`Fetch models`:n.phase===`discovering`?`Fetching models...`:`Refresh models`}
3338
+ ${n?.phase===`discovering`?aT():tT()} ${n===void 0?`Fetch models`:n.phase===`discovering`?`Fetching models...`:`Refresh models`}
3307
3339
  </button>
3308
- <button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${Qw()} Delete provider</button>
3340
+ <button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${eT()} Delete provider</button>
3309
3341
  </div>
3310
3342
  </div>
3311
3343
 
3312
3344
  <div class="field-stack provider-name-field">
3313
3345
  <label for="provider-name">Provider name</label>
3314
3346
  <div class="inline-field">
3315
- <input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=Dw(e),this.renameError=``}}>
3347
+ <input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=kw(e),this.renameError=``}}>
3316
3348
  <button type="button" class="secondary" ?disabled=${this.providerNameDraft.trim()===``||this.providerNameDraft===e} @click=${()=>{this.renameSelectedProvider(e)}}>Rename</button>
3317
3349
  </div>
3318
3350
  ${this.renameError===``?null:g`<span class="field-error">${this.renameError}</span>`}
@@ -3320,19 +3352,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3320
3352
 
3321
3353
  <div class="field-stack">
3322
3354
  <label for="provider-base-url">Base URL</label>
3323
- <input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:Ew(Dw(n))})}}>
3355
+ <input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:Ow(kw(n))})}}>
3324
3356
  </div>
3325
3357
 
3326
3358
  <div class="field-stack">
3327
3359
  <label for="provider-api-key">API key source</label>
3328
- <input id="provider-api-key" class="mono" type="password" autocomplete="off" .value=${t.apiKey??``} placeholder="ENV_VAR_NAME, !command, or literal key" @input=${n=>{this.replaceProvider(e,{...t,apiKey:Ew(Dw(n))})}}>
3360
+ <input id="provider-api-key" class="mono" type="password" autocomplete="off" .value=${t.apiKey??``} placeholder="ENV_VAR_NAME, !command, or literal key" @input=${n=>{this.replaceProvider(e,{...t,apiKey:Ow(kw(n))})}}>
3329
3361
  <span class="help-text">Use an environment variable name, prefix a command with <code>!</code>, or configure built-in provider credentials through Authentication.</span>
3330
3362
  </div>
3331
3363
 
3332
3364
  <div class="field-stack">
3333
3365
  <label for="provider-api">API format</label>
3334
- <select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:Dw(n)})}}>
3335
- ${ow(i).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
3366
+ <select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:kw(n)})}}>
3367
+ ${cw(i).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
3336
3368
  </select>
3337
3369
  </div>
3338
3370
 
@@ -3347,7 +3379,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3347
3379
  </div>
3348
3380
  </details>
3349
3381
  </div>
3350
- `}renderModelDetail(e,t,n,r){let i=this.modelTests[Bw(e,r)];return g`
3382
+ `}renderModelDetail(e,t,n,r){let i=this.modelTests[Hw(e,r)];return g`
3351
3383
  <div class="detail-content">
3352
3384
  <div class="detail-heading">
3353
3385
  <div>
@@ -3355,35 +3387,35 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3355
3387
  <h2>${n.id.trim()===``?`New model`:n.id}</h2>
3356
3388
  </div>
3357
3389
  <div class="model-actions">
3358
- ${i===void 0?null:g`<span class="connection-state ${i.phase}">${Gw(i)}</span>`}
3390
+ ${i===void 0?null:g`<span class="connection-state ${i.phase}">${qw(i)}</span>`}
3359
3391
  <button type="button" class="secondary" ?disabled=${n.id.trim()===``||i?.phase===`testing`} @click=${()=>{this.testModel(e,r)}}>
3360
- ${i?.phase===`testing`?rT():nT()} ${i?.phase===`testing`?`Testing...`:`Test`}
3392
+ ${i?.phase===`testing`?aT():iT()} ${i?.phase===`testing`?`Testing...`:`Test`}
3361
3393
  </button>
3362
- <button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${Qw()} Remove</button>
3394
+ <button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${eT()} Remove</button>
3363
3395
  </div>
3364
3396
  </div>
3365
3397
 
3366
- ${i===void 0?null:g`<div class="connection-detail ${i.phase}">${Kw(i)}</div>`}
3398
+ ${i===void 0?null:g`<div class="connection-detail ${i.phase}">${Jw(i)}</div>`}
3367
3399
 
3368
3400
  <div class="field-grid two-columns">
3369
3401
  ${this.renderModelIdField(e,n,r)}
3370
3402
  <div class="field-stack">
3371
3403
  <label for="model-name">Display name</label>
3372
- <input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:Ew(Dw(t))})}}>
3404
+ <input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:Ow(kw(t))})}}>
3373
3405
  </div>
3374
3406
  </div>
3375
3407
 
3376
3408
  <div class="field-stack">
3377
3409
  <label for="model-api">API override</label>
3378
- <select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:Ew(Dw(t))})}}>
3410
+ <select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:Ow(kw(t))})}}>
3379
3411
  <option value="">Inherit provider API</option>
3380
- ${ow(n.api).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
3412
+ ${cw(n.api).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
3381
3413
  </select>
3382
3414
  </div>
3383
3415
 
3384
3416
  <div class="switch-row">
3385
3417
  ${this.renderCheck(`Reasoning / thinking`,n.reasoning===!0,t=>{this.replaceModel(e,r,{...n,reasoning:t||void 0})})}
3386
- ${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?Mw(n.input):Nw(n.input)})})}
3418
+ ${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?Pw(n.input):Fw(n.input)})})}
3387
3419
  </div>
3388
3420
 
3389
3421
  ${n.reasoning===!0?g`
@@ -3393,10 +3425,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3393
3425
  <span class="section-label">Thinking configuration</span>
3394
3426
  <p>Map Pi thinking levels to values accepted by this model, or disable a level.</p>
3395
3427
  </div>
3396
- ${this.renderCheck(`DeepSeek thinking compatibility`,Pw(n),t=>{this.replaceModel(e,r,Fw(n,t))})}
3428
+ ${this.renderCheck(`DeepSeek thinking compatibility`,Iw(n),t=>{this.replaceModel(e,r,Lw(n,t))})}
3397
3429
  </div>
3398
3430
  <div class="thinking-map">
3399
- ${cw.map(t=>this.renderThinkingLevel(e,r,n,t))}
3431
+ ${uw.map(t=>this.renderThinkingLevel(e,r,n,t))}
3400
3432
  </div>
3401
3433
  </section>
3402
3434
  `:null}
@@ -3404,11 +3436,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3404
3436
  <div class="field-grid two-columns">
3405
3437
  <div class="field-stack">
3406
3438
  <label for="context-window">Context window (tokens)</label>
3407
- <input id="context-window" type="number" min="0" inputmode="numeric" .value=${kw(n.contextWindow)} placeholder="128000" @input=${t=>{this.replaceModel(e,r,{...n,contextWindow:Aw(Dw(t))})}}>
3439
+ <input id="context-window" type="number" min="0" inputmode="numeric" .value=${jw(n.contextWindow)} placeholder="128000" @input=${t=>{this.replaceModel(e,r,{...n,contextWindow:Mw(kw(t))})}}>
3408
3440
  </div>
3409
3441
  <div class="field-stack">
3410
3442
  <label for="max-tokens">Max output tokens</label>
3411
- <input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${kw(n.maxTokens)} placeholder="16384" @input=${t=>{this.replaceModel(e,r,{...n,maxTokens:Aw(Dw(t))})}}>
3443
+ <input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${jw(n.maxTokens)} placeholder="16384" @input=${t=>{this.replaceModel(e,r,{...n,maxTokens:Mw(kw(t))})}}>
3412
3444
  </div>
3413
3445
  </div>
3414
3446
 
@@ -3435,14 +3467,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3435
3467
  `}renderModelIdField(e,t,n){let r=this.discoveredModels[e]?.models;if(r===void 0)return g`
3436
3468
  <div class="field-stack">
3437
3469
  <label for="model-id">Model ID <span aria-hidden="true">*</span></label>
3438
- <input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:Dw(r)})}}>
3470
+ <input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:kw(r)})}}>
3439
3471
  </div>
3440
3472
  `;let i=t.id.trim()===``||r.some(e=>e.id===t.id)?r:[{id:t.id,...t.name===void 0?{}:{name:t.name}},...r];return g`
3441
3473
  <div class="field-stack">
3442
3474
  <label for="model-id">Model ID <span aria-hidden="true">*</span></label>
3443
- <select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,Dw(t))}}>
3475
+ <select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,kw(t))}}>
3444
3476
  ${t.id.trim()===``?g`<option value="" disabled>Select a model</option>`:null}
3445
- ${sw(i,t.id).map(({candidate:e,selected:t})=>g`<option value=${e.id} .selected=${t}>${e.name===void 0?e.id:`${e.name} (${e.id})`}</option>`)}
3477
+ ${lw(i,t.id).map(({candidate:e,selected:t})=>g`<option value=${e.id} .selected=${t}>${e.name===void 0?e.id:`${e.name} (${e.id})`}</option>`)}
3446
3478
  </select>
3447
3479
  </div>
3448
3480
  `}renderThinkingLevel(e,t,n,r){let i=n.thinkingLevelMap?.[r],a=i===void 0?`default`:i===null?`disabled`:`custom`,o=typeof i==`string`?i:``;return g`
@@ -3454,26 +3486,26 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3454
3486
  </div>
3455
3487
  <label class="custom-thinking">
3456
3488
  <span>Custom</span>
3457
- <input class="mono" .value=${o} placeholder=${r} @focus=${()=>{this.setThinkingLevel(e,t,n,r,`custom`,o||r)}} @input=${i=>{this.setThinkingLevel(e,t,n,r,`custom`,Dw(i))}}>
3489
+ <input class="mono" .value=${o} placeholder=${r} @focus=${()=>{this.setThinkingLevel(e,t,n,r,`custom`,o||r)}} @input=${i=>{this.setThinkingLevel(e,t,n,r,`custom`,kw(i))}}>
3458
3490
  </label>
3459
3491
  </div>
3460
3492
  `}renderCostField(e,t,n,r,i){let a=`cost-${t}`;return g`
3461
3493
  <div class="field-stack">
3462
3494
  <label for=${a}>${e}</label>
3463
- <input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${kw(i.cost?.[t])} placeholder="0" @input=${e=>{this.setCost(n,r,i,t,jw(Dw(e)))}}>
3495
+ <input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${jw(i.cost?.[t])} placeholder="0" @input=${e=>{this.setCost(n,r,i,t,Nw(kw(e)))}}>
3464
3496
  </div>
3465
3497
  `}renderCheck(e,t,n){return g`
3466
3498
  <label class="check-row">
3467
- <input type="checkbox" .checked=${t} @change=${e=>{n(Ow(e))}}>
3499
+ <input type="checkbox" .checked=${t} @change=${e=>{n(Aw(e))}}>
3468
3500
  <span>${e}</span>
3469
3501
  </label>
3470
3502
  `}renderJsonField(e,t,n,r){let i=`advanced-${t}`,a=this.advancedErrors[t];return g`
3471
3503
  <div class="field-stack">
3472
3504
  <label for=${i}>${e} (JSON object)</label>
3473
- <textarea id=${i} class="mono" rows="4" .value=${Lw(n)} @change=${e=>{r(Dw(e))}}></textarea>
3505
+ <textarea id=${i} class="mono" rows="4" .value=${zw(n)} @change=${e=>{r(kw(e))}}></textarea>
3474
3506
  ${a===void 0?null:g`<span class="field-error">${a}</span>`}
3475
3507
  </div>
3476
- `}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=Cw(await this.modelsApi.config(t));if(!this.isCurrentLoad(e,t))return;this.config=n,this.selection=ww(this.selection,n),this.providerNameDraft=this.selection?.type===`provider`?this.selection.providerName:``,this.renameError=``,this.advancedErrors={},this.modelTests={}}catch(n){this.isCurrentLoad(e,t)&&(this.error=`Failed to load models configuration: ${Jw(n)}`)}finally{this.isCurrentLoad(e,t)&&(this.loading=!1)}}async saveConfig(){if(this.saving||this.loading)return;let e=this.machineId();this.saving=!0,this.error=``,this.savedMessage=``;try{if(await this.modelsApi.save(this.config,e),e!==this.machineId())return;this.setSavedMessage(`Saved and reloaded models for ${this.machineLabel()}.`),this.onSaved?.()}catch(t){e===this.machineId()&&(this.error=`Failed to save models configuration: ${Jw(t)}`)}finally{e===this.machineId()&&(this.saving=!1)}}async testModel(e,t){let n=this.config.providers?.[e],r=n?.models?.[t];if(n===void 0||r===void 0)return;let i=Bw(e,t);if(r.id.trim()===``){this.modelTests={...this.modelTests,[i]:{phase:`error`,message:`Model ID is required.`}};return}let a=this.machineId();this.modelTests={...this.modelTests,[i]:{phase:`testing`}};try{let t=await this.modelsApi.test({providerName:e,provider:n,model:r},a);if(a!==this.machineId())return;this.modelTests={...this.modelTests,[i]:t.ok?{phase:`success`,result:t}:Ww(t)}}catch(e){a===this.machineId()&&(this.modelTests={...this.modelTests,[i]:{phase:`error`,message:Jw(e)}})}}async discoverModels(e){let t=this.config.providers?.[e];if(t===void 0)return;let n=this.nextModelDiscoveryRequest(e),r=this.machineId(),i=this.discoveredModels[e];this.error=``,this.discoveredModels={...this.discoveredModels,[e]:i?.models===void 0?{phase:`discovering`}:{phase:`discovering`,models:i.models}};try{let i=await this.modelsApi.discover({providerName:e,provider:t},r);if(!this.isCurrentModelDiscovery(n,r,e,t))return;this.discoveredModels={...this.discoveredModels,[e]:{phase:`ready`,models:i.models}}}catch(a){if(!this.isCurrentModelDiscovery(n,r,e,t))return;this.discoveredModels=i===void 0?Uw(this.discoveredModels,e):{...this.discoveredModels,[e]:i},this.error=`Failed to fetch models for ${e}: ${Jw(a)}`}}selectProvider(e){this.selection={type:`provider`,providerName:e},this.providerNameDraft=e,this.renameError=``}selectModel(e,t){this.selection={type:`model`,providerName:e,index:t},this.providerNameDraft=``,this.renameError=``}addCustomProvider(){let e=lw(this.config);this.config=e.config,this.selectProvider(e.providerName)}deleteProvider(e){this.clearProviderDiscovery(e),this.config=fw(this.config,e),this.modelTests=Vw(this.modelTests,e);let t=Object.keys(this.config.providers??{})[0];t===void 0?(this.selection=void 0,this.providerNameDraft=``):this.selectProvider(t)}renameSelectedProvider(e){let t=uw(this.config,e,this.providerNameDraft);if(`error`in t){this.renameError=t.error;return}let n=this.providerNameDraft.trim();this.clearProviderDiscovery(e),this.config=t.config,this.modelTests=Hw(this.modelTests,e,n),this.selectProvider(n)}replaceProvider(e,t){this.invalidateProviderDiscovery(e),this.config=dw(this.config,e,t),this.modelTests=Vw(this.modelTests,e)}addModel(e){let t=this.config.providers?.[e]?.models?.length??0;this.config=pw(this.config,e),this.selectModel(e,t)}deleteModel(e,t){this.config=hw(this.config,e,t),this.modelTests=Vw(this.modelTests,e),this.selectProvider(e)}replaceModel(e,t,n){this.config=mw(this.config,e,t,n);let r=Bw(e,t);this.modelTests[r]!==void 0&&(this.modelTests=Uw(this.modelTests,r))}selectDiscoveredModel(e,t,n){let r=this.config.providers?.[e]?.models?.[t],i=this.discoveredModels[e]?.models?.find(e=>e.id===n);r===void 0||i===void 0||this.replaceModel(e,t,{...r,id:i.id,name:i.name??i.id})}invalidateProviderDiscovery(e){this.nextModelDiscoveryRequest(e);let t=this.discoveredModels[e];if(t?.phase===`discovering`){if(t.models===void 0){this.discoveredModels=Uw(this.discoveredModels,e);return}this.discoveredModels={...this.discoveredModels,[e]:{phase:`ready`,models:t.models}}}}clearProviderDiscovery(e){this.nextModelDiscoveryRequest(e),this.discoveredModels[e]!==void 0&&(this.discoveredModels=Uw(this.discoveredModels,e))}setThinkingLevel(e,t,n,r,i,a){this.replaceModel(e,t,{...n,thinkingLevelMap:gw(n.thinkingLevelMap,r,i,a)})}setCost(e,t,n,r,i){let a={...n.cost??{},[r]:i};if(Object.values(a).every(e=>e===void 0)){this.replaceModel(e,t,{...n,cost:void 0});return}this.replaceModel(e,t,{...n,cost:a})}updateProviderHeaders(e,t,n){let r=Iw(n),i=`headers`;if(!r.ok){this.setAdvancedError(i,r.error);return}if(r.value!==void 0&&!Rw(r.value)){this.setAdvancedError(i,`Headers must map string names to string values.`);return}this.clearAdvancedError(i),this.replaceProvider(e,{...t,headers:r.value===void 0?void 0:zw(r.value)})}updateProviderObject(e,t,n,r){let i=Iw(r),a=n===`compat`?`compat`:`model-overrides`;if(!i.ok){this.setAdvancedError(a,i.error);return}this.clearAdvancedError(a),this.replaceProvider(e,{...t,[n]:i.value})}updateModelObject(e,t,n,r,i){let a=Iw(i),o=`model-compat`;if(!a.ok){this.setAdvancedError(o,a.error);return}this.clearAdvancedError(o),this.replaceModel(e,t,{...n,[r]:a.value})}setAdvancedError(e,t){this.advancedErrors={...this.advancedErrors,[e]:t}}clearAdvancedError(e){this.advancedErrors[e]!==void 0&&(this.advancedErrors=Uw(this.advancedErrors,e))}configureAuth(){this.onConfigureAuth?.()}close(){this.onClose?.()}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}resetForMachineChange(){this.loadRequestSequence+=1,this.modelDiscoveryRequestSequences.clear(),this.config={providers:{}},this.loading=!0,this.saving=!1,this.error=``,this.savedMessage=``,this.selection=void 0,this.providerNameDraft=``,this.renameError=``,this.advancedErrors={},this.modelTests={},this.discoveredModels={}}machineId(){return Tw(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}isCurrentLoad(e,t){return e===this.loadRequestSequence&&t===this.machineId()}isCurrentModelDiscovery(e,t,n,r){return e===this.modelDiscoveryRequestSequences.get(n)&&t===this.machineId()&&this.config.providers?.[n]===r}nextModelDiscoveryRequest(e){let t=++this.modelDiscoverySequence;return this.modelDiscoveryRequestSequences.set(e,t),t}setSavedMessage(e){this.savedMessageTimer!==void 0&&clearTimeout(this.savedMessageTimer),this.savedMessage=e,this.savedMessageTimer=setTimeout(()=>{this.savedMessage=``,this.savedMessageTimer=void 0},3e3)}static{this.styles=h`
3508
+ `}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=Tw(await this.modelsApi.config(t));if(!this.isCurrentLoad(e,t))return;this.config=n,this.selection=Ew(this.selection,n),this.providerNameDraft=this.selection?.type===`provider`?this.selection.providerName:``,this.renameError=``,this.advancedErrors={},this.modelTests={}}catch(n){this.isCurrentLoad(e,t)&&(this.error=`Failed to load models configuration: ${Xw(n)}`)}finally{this.isCurrentLoad(e,t)&&(this.loading=!1)}}async saveConfig(){if(this.saving||this.loading)return;let e=this.machineId();this.saving=!0,this.error=``,this.savedMessage=``;try{if(await this.modelsApi.save(this.config,e),e!==this.machineId())return;this.setSavedMessage(`Saved and reloaded models for ${this.machineLabel()}.`),this.onSaved?.()}catch(t){e===this.machineId()&&(this.error=`Failed to save models configuration: ${Xw(t)}`)}finally{e===this.machineId()&&(this.saving=!1)}}async testModel(e,t){let n=this.config.providers?.[e],r=n?.models?.[t];if(n===void 0||r===void 0)return;let i=Hw(e,t);if(r.id.trim()===``){this.modelTests={...this.modelTests,[i]:{phase:`error`,message:`Model ID is required.`}};return}let a=this.machineId();this.modelTests={...this.modelTests,[i]:{phase:`testing`}};try{let t=await this.modelsApi.test({providerName:e,provider:n,model:r},a);if(a!==this.machineId())return;this.modelTests={...this.modelTests,[i]:t.ok?{phase:`success`,result:t}:Kw(t)}}catch(e){a===this.machineId()&&(this.modelTests={...this.modelTests,[i]:{phase:`error`,message:Xw(e)}})}}async discoverModels(e){let t=this.config.providers?.[e];if(t===void 0)return;let n=this.nextModelDiscoveryRequest(e),r=this.machineId(),i=this.discoveredModels[e];this.error=``,this.discoveredModels={...this.discoveredModels,[e]:i?.models===void 0?{phase:`discovering`}:{phase:`discovering`,models:i.models}};try{let i=await this.modelsApi.discover({providerName:e,provider:t},r);if(!this.isCurrentModelDiscovery(n,r,e,t))return;this.discoveredModels={...this.discoveredModels,[e]:{phase:`ready`,models:i.models}}}catch(a){if(!this.isCurrentModelDiscovery(n,r,e,t))return;this.discoveredModels=i===void 0?Gw(this.discoveredModels,e):{...this.discoveredModels,[e]:i},this.error=`Failed to fetch models for ${e}: ${Xw(a)}`}}selectProvider(e){this.selection={type:`provider`,providerName:e},this.providerNameDraft=e,this.renameError=``}selectModel(e,t){this.selection={type:`model`,providerName:e,index:t},this.providerNameDraft=``,this.renameError=``}addCustomProvider(){let e=dw(this.config);this.config=e.config,this.selectProvider(e.providerName)}deleteProvider(e){this.clearProviderDiscovery(e),this.config=mw(this.config,e),this.modelTests=Uw(this.modelTests,e);let t=Object.keys(this.config.providers??{})[0];t===void 0?(this.selection=void 0,this.providerNameDraft=``):this.selectProvider(t)}renameSelectedProvider(e){let t=fw(this.config,e,this.providerNameDraft);if(`error`in t){this.renameError=t.error;return}let n=this.providerNameDraft.trim();this.clearProviderDiscovery(e),this.config=t.config,this.modelTests=Ww(this.modelTests,e,n),this.selectProvider(n)}replaceProvider(e,t){this.invalidateProviderDiscovery(e),this.config=pw(this.config,e,t),this.modelTests=Uw(this.modelTests,e)}addModel(e){let t=this.config.providers?.[e]?.models?.length??0;this.config=hw(this.config,e),this.selectModel(e,t)}deleteModel(e,t){this.config=_w(this.config,e,t),this.modelTests=Uw(this.modelTests,e),this.selectProvider(e)}replaceModel(e,t,n){this.config=gw(this.config,e,t,n);let r=Hw(e,t);this.modelTests[r]!==void 0&&(this.modelTests=Gw(this.modelTests,r))}selectDiscoveredModel(e,t,n){let r=this.config.providers?.[e]?.models?.[t],i=this.discoveredModels[e]?.models?.find(e=>e.id===n);r===void 0||i===void 0||this.replaceModel(e,t,{...r,id:i.id,name:i.name??i.id})}invalidateProviderDiscovery(e){this.nextModelDiscoveryRequest(e);let t=this.discoveredModels[e];if(t?.phase===`discovering`){if(t.models===void 0){this.discoveredModels=Gw(this.discoveredModels,e);return}this.discoveredModels={...this.discoveredModels,[e]:{phase:`ready`,models:t.models}}}}clearProviderDiscovery(e){this.nextModelDiscoveryRequest(e),this.discoveredModels[e]!==void 0&&(this.discoveredModels=Gw(this.discoveredModels,e))}setThinkingLevel(e,t,n,r,i,a){this.replaceModel(e,t,{...n,thinkingLevelMap:vw(n.thinkingLevelMap,r,i,a)})}setCost(e,t,n,r,i){let a={...n.cost??{},[r]:i};if(Object.values(a).every(e=>e===void 0)){this.replaceModel(e,t,{...n,cost:void 0});return}this.replaceModel(e,t,{...n,cost:a})}updateProviderHeaders(e,t,n){let r=Rw(n),i=`headers`;if(!r.ok){this.setAdvancedError(i,r.error);return}if(r.value!==void 0&&!Bw(r.value)){this.setAdvancedError(i,`Headers must map string names to string values.`);return}this.clearAdvancedError(i),this.replaceProvider(e,{...t,headers:r.value===void 0?void 0:Vw(r.value)})}updateProviderObject(e,t,n,r){let i=Rw(r),a=n===`compat`?`compat`:`model-overrides`;if(!i.ok){this.setAdvancedError(a,i.error);return}this.clearAdvancedError(a),this.replaceProvider(e,{...t,[n]:i.value})}updateModelObject(e,t,n,r,i){let a=Rw(i),o=`model-compat`;if(!a.ok){this.setAdvancedError(o,a.error);return}this.clearAdvancedError(o),this.replaceModel(e,t,{...n,[r]:a.value})}setAdvancedError(e,t){this.advancedErrors={...this.advancedErrors,[e]:t}}clearAdvancedError(e){this.advancedErrors[e]!==void 0&&(this.advancedErrors=Gw(this.advancedErrors,e))}configureAuth(){this.onConfigureAuth?.()}close(){this.onClose?.()}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}resetForMachineChange(){this.loadRequestSequence+=1,this.modelDiscoveryRequestSequences.clear(),this.config={providers:{}},this.loading=!0,this.saving=!1,this.error=``,this.savedMessage=``,this.selection=void 0,this.providerNameDraft=``,this.renameError=``,this.advancedErrors={},this.modelTests={},this.discoveredModels={}}machineId(){return Dw(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}isCurrentLoad(e,t){return e===this.loadRequestSequence&&t===this.machineId()}isCurrentModelDiscovery(e,t,n,r){return e===this.modelDiscoveryRequestSequences.get(n)&&t===this.machineId()&&this.config.providers?.[n]===r}nextModelDiscoveryRequest(e){let t=++this.modelDiscoverySequence;return this.modelDiscoveryRequestSequences.set(e,t),t}setSavedMessage(e){this.savedMessageTimer!==void 0&&clearTimeout(this.savedMessageTimer),this.savedMessage=e,this.savedMessageTimer=setTimeout(()=>{this.savedMessage=``,this.savedMessageTimer=void 0},3e3)}static{this.styles=h`
3477
3509
  :host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
3478
3510
  .backdrop { position: absolute; inset: 0; display: grid; place-items: center; box-sizing: border-box; padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); background: var(--pi-overlay); }
3479
3511
  .dialog { width: min(920px, 100%); height: min(78dvh, 760px); max-height: 100%; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); }
@@ -3581,16 +3613,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3581
3613
  .thinking-row { grid-template-columns: 58px minmax(0, 1fr); }
3582
3614
  .custom-thinking { grid-column: 1 / -1; }
3583
3615
  }
3584
- `}};B([x({attribute:!1})],Sw.prototype,`machine`,void 0),B([x({attribute:!1})],Sw.prototype,`modelsApi`,void 0),B([x({attribute:!1})],Sw.prototype,`onClose`,void 0),B([x({attribute:!1})],Sw.prototype,`onConfigureAuth`,void 0),B([x({attribute:!1})],Sw.prototype,`onSaved`,void 0),B([S()],Sw.prototype,`config`,void 0),B([S()],Sw.prototype,`loading`,void 0),B([S()],Sw.prototype,`saving`,void 0),B([S()],Sw.prototype,`error`,void 0),B([S()],Sw.prototype,`savedMessage`,void 0),B([S()],Sw.prototype,`selection`,void 0),B([S()],Sw.prototype,`providerNameDraft`,void 0),B([S()],Sw.prototype,`renameError`,void 0),B([S()],Sw.prototype,`advancedErrors`,void 0),B([S()],Sw.prototype,`modelTests`,void 0),B([S()],Sw.prototype,`discoveredModels`,void 0),Sw=B([b(`models-config-dialog`)],Sw);function Cw(e){return e.providers===void 0?{...e,providers:{}}:e}function ww(e,t){if(e?.type===`provider`&&t.providers?.[e.providerName]!==void 0||e?.type===`model`&&t.providers?.[e.providerName]?.models?.[e.index]!==void 0)return e;let n=Object.keys(t.providers??{})[0];return n===void 0?void 0:{type:`provider`,providerName:n}}function Tw(e){if(!qw(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function Ew(e){return e.trim()===``?void 0:e}function Dw(e){let t=e.target;return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.value:``}function Ow(e){return e.target instanceof HTMLInputElement&&e.target.checked}function kw(e){return e===void 0?``:String(e)}function Aw(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isInteger(n)&&n>=0?n:void 0}function jw(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function Mw(e){let t=e??[`text`];return t.includes(`image`)?[...t]:[...t,`image`]}function Nw(e){let t=(e??[]).filter(e=>e!==`image`);return t.length===0?void 0:t}function Pw(e){return e.compat?.thinkingFormat===`deepseek`}function Fw(e,t){if(t)return{...e,compat:{...e.compat??{},...xw}};if(e.compat===void 0)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length===0?void 0:n}}function Iw(e){if(e.trim()===``)return{ok:!0,value:void 0};try{let t=JSON.parse(e);return qw(t)?{ok:!0,value:t}:{ok:!1,error:`Value must be a JSON object.`}}catch(e){return{ok:!1,error:`Invalid JSON: ${Jw(e)}`}}}function Lw(e){return e===void 0?``:JSON.stringify(e,null,2)}function Rw(e){return Object.values(e).every(e=>typeof e==`string`)}function zw(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function Bw(e,t){return`${e}\u0000${String(t)}`}function Vw(e,t){let n=`${t}\u0000`,r={};for(let[t,i]of Object.entries(e))t.startsWith(n)||(r[t]=i);return r}function Hw(e,t,n){let r=`${t}\u0000`,i=`${n}\u0000`,a={};for(let[t,n]of Object.entries(e)){let e=t.startsWith(r)?`${i}${t.slice(r.length)}`:t;a[e]=n}return a}function Uw(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function Ww(e){return{phase:`error`,message:e.error??`Model returned an error.`,...e.latencyMs===void 0?{}:{latencyMs:e.latencyMs},...e.status===void 0?{}:{status:e.status}}}function Gw(e){return e.phase===`testing`?`Testing connection`:e.phase===`success`?e.result.latencyMs===void 0?`Connected`:`Connected in ${String(e.result.latencyMs)} ms`:`Connection failed`}function Kw(e){if(e.phase===`testing`)return`Sending a small test request...`;if(e.phase===`success`){let t=[e.result.status===void 0?void 0:`HTTP ${String(e.result.status)}`,e.result.latencyMs===void 0?void 0:`${String(e.result.latencyMs)} ms`,e.result.responseText===void 0||e.result.responseText===``?void 0:e.result.responseText].filter(e=>e!==void 0);return t.length===0?`Connection succeeded.`:t.join(` - `)}return[e.status===void 0?void 0:`HTTP ${String(e.status)}`,e.latencyMs===void 0?void 0:`${String(e.latencyMs)} ms`,e.message].filter(e=>e!==void 0).join(` - `)}function qw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jw(e){return e instanceof Error?e.message:String(e)}function Yw(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="4" y="4" width="16" height="16" rx="2"></rect><rect x="9" y="9" width="6" height="6"></rect><path d="M9 1v3m6-3v3M9 20v3m6-3v3M20 9h3m-3 5h3M1 9h3m-3 5h3"></path></svg>`}function Xw(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="7"></circle><path d="M12 8v4l3 2"></path></svg>`}function Zw(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function Qw(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M4 7h16M10 11v6m4-6v6M9 7l1-3h4l1 3m-9 0 1 13h10l1-13"></path></svg>`}function $w(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M20 11a8 8 0 1 0 2 5.5"></path><path d="M20 4v7h-7"></path></svg>`}function eT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}function tT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="8" cy="15" r="4"></circle><path d="m11 12 9-9m-3 0h3v3"></path></svg>`}function nT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 22v-5M8 4v5m8-5v5M7 9h10v3a5 5 0 0 1-10 0V9Z"></path></svg>`}function rT(){return _`<svg class="svg-icon spin" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="8" opacity=".25"></circle><path d="M20 12a8 8 0 0 0-8-8"></path></svg>`}var J=class extends y{constructor(...e){super(...e),this.cwd=``,this.skillsApi=$a,this.skills=[],this.loading=!0,this.loadError=``,this.togglingPaths=new Set,this.saveError=``,this.addMode=!1,this.searchQuery=``,this.searchResults=[],this.searching=!1,this.searchError=``,this.installError=``,this.newlyInstalledKeys=new Set,this.installScope=`global`,this.updateStatuses={},this.checkingUpdateKeys=new Set,this.checkingAll=!1,this.updateError=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSkills()}updated(e){let t=e.has(`machine`)&&iT(e.get(`machine`))!==this.machineId(),n=e.has(`cwd`)&&e.get(`cwd`)!==this.cwd;(t||n)&&(this.resetForTargetChange(),this.isConnected&&this.loadSkills())}render(){let e=this.selectedSkill();return g`
3616
+ `}};B([x({attribute:!1})],ww.prototype,`machine`,void 0),B([x({attribute:!1})],ww.prototype,`modelsApi`,void 0),B([x({attribute:!1})],ww.prototype,`onClose`,void 0),B([x({attribute:!1})],ww.prototype,`onConfigureAuth`,void 0),B([x({attribute:!1})],ww.prototype,`onSaved`,void 0),B([S()],ww.prototype,`config`,void 0),B([S()],ww.prototype,`loading`,void 0),B([S()],ww.prototype,`saving`,void 0),B([S()],ww.prototype,`error`,void 0),B([S()],ww.prototype,`savedMessage`,void 0),B([S()],ww.prototype,`selection`,void 0),B([S()],ww.prototype,`providerNameDraft`,void 0),B([S()],ww.prototype,`renameError`,void 0),B([S()],ww.prototype,`advancedErrors`,void 0),B([S()],ww.prototype,`modelTests`,void 0),B([S()],ww.prototype,`discoveredModels`,void 0),ww=B([b(`models-config-dialog`)],ww);function Tw(e){return e.providers===void 0?{...e,providers:{}}:e}function Ew(e,t){if(e?.type===`provider`&&t.providers?.[e.providerName]!==void 0||e?.type===`model`&&t.providers?.[e.providerName]?.models?.[e.index]!==void 0)return e;let n=Object.keys(t.providers??{})[0];return n===void 0?void 0:{type:`provider`,providerName:n}}function Dw(e){if(!Yw(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function Ow(e){return e.trim()===``?void 0:e}function kw(e){let t=e.target;return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.value:``}function Aw(e){return e.target instanceof HTMLInputElement&&e.target.checked}function jw(e){return e===void 0?``:String(e)}function Mw(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isInteger(n)&&n>=0?n:void 0}function Nw(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function Pw(e){let t=e??[`text`];return t.includes(`image`)?[...t]:[...t,`image`]}function Fw(e){let t=(e??[]).filter(e=>e!==`image`);return t.length===0?void 0:t}function Iw(e){return e.compat?.thinkingFormat===`deepseek`}function Lw(e,t){if(t)return{...e,compat:{...e.compat??{},...Cw}};if(e.compat===void 0)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length===0?void 0:n}}function Rw(e){if(e.trim()===``)return{ok:!0,value:void 0};try{let t=JSON.parse(e);return Yw(t)?{ok:!0,value:t}:{ok:!1,error:`Value must be a JSON object.`}}catch(e){return{ok:!1,error:`Invalid JSON: ${Xw(e)}`}}}function zw(e){return e===void 0?``:JSON.stringify(e,null,2)}function Bw(e){return Object.values(e).every(e=>typeof e==`string`)}function Vw(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function Hw(e,t){return`${e}\u0000${String(t)}`}function Uw(e,t){let n=`${t}\u0000`,r={};for(let[t,i]of Object.entries(e))t.startsWith(n)||(r[t]=i);return r}function Ww(e,t,n){let r=`${t}\u0000`,i=`${n}\u0000`,a={};for(let[t,n]of Object.entries(e)){let e=t.startsWith(r)?`${i}${t.slice(r.length)}`:t;a[e]=n}return a}function Gw(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function Kw(e){return{phase:`error`,message:e.error??`Model returned an error.`,...e.latencyMs===void 0?{}:{latencyMs:e.latencyMs},...e.status===void 0?{}:{status:e.status}}}function qw(e){return e.phase===`testing`?`Testing connection`:e.phase===`success`?e.result.latencyMs===void 0?`Connected`:`Connected in ${String(e.result.latencyMs)} ms`:`Connection failed`}function Jw(e){if(e.phase===`testing`)return`Sending a small test request...`;if(e.phase===`success`){let t=[e.result.status===void 0?void 0:`HTTP ${String(e.result.status)}`,e.result.latencyMs===void 0?void 0:`${String(e.result.latencyMs)} ms`,e.result.responseText===void 0||e.result.responseText===``?void 0:e.result.responseText].filter(e=>e!==void 0);return t.length===0?`Connection succeeded.`:t.join(` - `)}return[e.status===void 0?void 0:`HTTP ${String(e.status)}`,e.latencyMs===void 0?void 0:`${String(e.latencyMs)} ms`,e.message].filter(e=>e!==void 0).join(` - `)}function Yw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xw(e){return e instanceof Error?e.message:String(e)}function Zw(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="4" y="4" width="16" height="16" rx="2"></rect><rect x="9" y="9" width="6" height="6"></rect><path d="M9 1v3m6-3v3M9 20v3m6-3v3M20 9h3m-3 5h3M1 9h3m-3 5h3"></path></svg>`}function Qw(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="7"></circle><path d="M12 8v4l3 2"></path></svg>`}function $w(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function eT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M4 7h16M10 11v6m4-6v6M9 7l1-3h4l1 3m-9 0 1 13h10l1-13"></path></svg>`}function tT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M20 11a8 8 0 1 0 2 5.5"></path><path d="M20 4v7h-7"></path></svg>`}function nT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}function rT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="8" cy="15" r="4"></circle><path d="m11 12 9-9m-3 0h3v3"></path></svg>`}function iT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 22v-5M8 4v5m8-5v5M7 9h10v3a5 5 0 0 1-10 0V9Z"></path></svg>`}function aT(){return _`<svg class="svg-icon spin" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="8" opacity=".25"></circle><path d="M20 12a8 8 0 0 0-8-8"></path></svg>`}var q=class extends y{constructor(...e){super(...e),this.cwd=``,this.skillsApi=$a,this.skills=[],this.loading=!0,this.loadError=``,this.togglingPaths=new Set,this.saveError=``,this.addMode=!1,this.searchQuery=``,this.searchResults=[],this.searching=!1,this.searchError=``,this.installError=``,this.newlyInstalledKeys=new Set,this.installScope=`global`,this.updateStatuses={},this.checkingUpdateKeys=new Set,this.checkingAll=!1,this.updateError=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSkills()}updated(e){let t=e.has(`machine`)&&oT(e.get(`machine`))!==this.machineId(),n=e.has(`cwd`)&&e.get(`cwd`)!==this.cwd;(t||n)&&(this.resetForTargetChange(),this.isConnected&&this.loadSkills())}render(){let e=this.selectedSkill();return g`
3585
3617
  <div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
3586
3618
  <section class="dialog" role="dialog" aria-modal="true" aria-labelledby="skills-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3587
3619
  <header>
3588
3620
  <div class="title-block">
3589
3621
  <h1 id="skills-dialog-title">Skills</h1>
3590
- <span class="target"><code>${cT(this.cwd)}</code> on ${this.machineLabel()}</span>
3622
+ <span class="target"><code>${uT(this.cwd)}</code> on ${this.machineLabel()}</span>
3591
3623
  </div>
3592
3624
  <button class="icon-button" type="button" title="Close skills configuration" aria-label="Close skills configuration" @click=${()=>{this.close()}}>
3593
- ${CT()}
3625
+ ${TT()}
3594
3626
  </button>
3595
3627
  </header>
3596
3628
 
@@ -3616,21 +3648,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3616
3648
  </div>
3617
3649
  <div class="skill-list-actions">
3618
3650
  <button class="add-skill" type="button" ?aria-pressed=${this.addMode} @click=${()=>{this.openAddMode()}}>
3619
- ${ST()} Add skill
3651
+ ${wT()} Add skill
3620
3652
  </button>
3621
3653
  </div>
3622
3654
  </aside>
3623
- `}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=fT(e,this.updateStatuses);return g`
3655
+ `}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=mT(e,this.updateStatuses);return g`
3624
3656
  <button class="skill-row ${t?`selected`:``}" type="button" @click=${()=>{this.selectSkill(e)}}>
3625
3657
  <span class="skill-indicator ${e.disableModelInvocation?`disabled`:``}" aria-hidden="true"></span>
3626
3658
  <span class="skill-name">${e.name}</span>
3627
3659
  ${n?.state===`update-available`?g`<span class="update-available-mark" title="Update available" aria-label="Update available">↑</span>`:null}
3628
3660
  </button>
3629
- `}renderSkillDetail(e){let t=oT(e),n=dT(e),r=n===void 0?void 0:this.updateStatuses[n],i=n!==void 0&&this.checkingUpdateKeys.has(n),a=n!==void 0&&this.updatingKey===n,o=!e.disableModelInvocation;return g`
3661
+ `}renderSkillDetail(e){let t=cT(e),n=pT(e),r=n===void 0?void 0:this.updateStatuses[n],i=n!==void 0&&this.checkingUpdateKeys.has(n),a=n!==void 0&&this.updatingKey===n,o=!e.disableModelInvocation;return g`
3630
3662
  <div class="detail-content">
3631
3663
  <div class="skill-meta-row">
3632
3664
  <span class="scope-tag ${t}">${t}</span>
3633
- <code class="skill-path" title=${e.filePath}>${sT(e,this.cwd)}</code>
3665
+ <code class="skill-path" title=${e.filePath}>${lT(e,this.cwd)}</code>
3634
3666
  <button
3635
3667
  class="skill-toggle ${o?`enabled`:``}"
3636
3668
  type="button"
@@ -3648,7 +3680,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3648
3680
  <section class="detail-section">
3649
3681
  <h2>Source</h2>
3650
3682
  <a class="source-link" href=${e.install.skillsShUrl} target="_blank" rel="noreferrer" title=${e.install.skillsShUrl}>
3651
- <code>${lT(e.install.skillsShUrl)} ↗</code>
3683
+ <code>${dT(e.install.skillsShUrl)} ↗</code>
3652
3684
  </a>
3653
3685
  </section>
3654
3686
  `}
@@ -3657,13 +3689,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3657
3689
  <section class="detail-section">
3658
3690
  <h2>Version</h2>
3659
3691
  <div class="version-row">
3660
- <code>${uT(r?.currentVersion??e.install.versionHash)}</code>
3692
+ <code>${fT(r?.currentVersion??e.install.versionHash)}</code>
3661
3693
  ${e.install.canCheckForUpdates?g`
3662
3694
  <button type="button" class="secondary compact-button" ?disabled=${i||a} @click=${()=>{this.checkForUpdates(e)}}>
3663
3695
  ${i?`Checking...`:`Check`}
3664
3696
  </button>
3665
3697
  `:null}
3666
- ${r?.state===`update-available`?g`<code class="update-version">${uT(r.latestVersion)}</code>`:null}
3698
+ ${r?.state===`update-available`?g`<code class="update-version">${fT(r.latestVersion)}</code>`:null}
3667
3699
  ${this.renderUpdateStatus(r,i)}
3668
3700
  ${r?.state===`update-available`?g`
3669
3701
  <button type="button" class="primary compact-button" ?disabled=${a||i} @click=${()=>{this.updateInstalledSkill(e)}}>
@@ -3685,7 +3717,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3685
3717
  <p>${e.description}</p>
3686
3718
  </section>
3687
3719
  </div>
3688
- `}renderUpdateStatus(e,t){if(!t&&(e===void 0||e.state===`update-available`))return null;let n=t?`Checking...`:e?.state===`up-to-date`?`Up to date`:e?.state===`unsupported`?`Automatic checks unavailable`:e?.message??`Check failed`;return g`<span class="update-state ${t?`checking`:e?.state??`error`}">${n}</span>`}renderAddPanel(){let e=this.installScope===`global`?`~/.pi/agent/skills/`:`${cT(this.cwd)}/.pi/skills/`;return g`
3720
+ `}renderUpdateStatus(e,t){if(!t&&(e===void 0||e.state===`update-available`))return null;let n=t?`Checking...`:e?.state===`up-to-date`?`Up to date`:e?.state===`unsupported`?`Automatic checks unavailable`:e?.message??`Check failed`;return g`<span class="update-state ${t?`checking`:e?.state??`error`}">${n}</span>`}renderAddPanel(){let e=this.installScope===`global`?`~/.pi/agent/skills/`:`${uT(this.cwd)}/.pi/skills/`;return g`
3689
3721
  <div class="detail-content add-panel">
3690
3722
  <div class="add-heading">
3691
3723
  <h2>Add Skill</h2>
@@ -3697,7 +3729,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3697
3729
  id="skill-search"
3698
3730
  .value=${this.searchQuery}
3699
3731
  placeholder="e.g. react, testing, deploy"
3700
- @input=${e=>{this.searchQuery=yT(e)}}
3732
+ @input=${e=>{this.searchQuery=xT(e)}}
3701
3733
  @keydown=${e=>{e.key===`Enter`&&(e.preventDefault(),this.searchSkills())}}
3702
3734
  >
3703
3735
  <button type="button" class="primary" ?disabled=${this.searching||this.searchQuery.trim()===``} @click=${()=>{this.searchSkills()}}>
@@ -3719,7 +3751,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3719
3751
 
3720
3752
  ${this.searchResults.length>0?g`<div class="search-results">${this.searchResults.map(e=>this.renderSearchResult(e))}</div>`:this.searching||this.searchError!==``?null:g`<p class="search-hint">Search <a href="https://skills.sh" target="_blank" rel="noreferrer">skills.sh</a> to discover and install skills for your agent.</p>`}
3721
3753
  </div>
3722
- `}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=mT(e.package);return g`
3754
+ `}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=gT(e.package);return g`
3723
3755
  <article class="search-result">
3724
3756
  <div class="search-result-copy">
3725
3757
  <strong>${r.skill??r.repository}</strong>
@@ -3748,7 +3780,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3748
3780
  </div>
3749
3781
  <button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
3750
3782
  </footer>
3751
- `}async loadSkills(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage skills.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.skillsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.skills=n.skills,this.selectedFilePath=aT(this.selectedFilePath,n.skills)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load skills: ${bT(n)}`)}finally{this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loading=!1)}}async toggleSkill(e){let t=this.target();if(t===void 0||this.togglingPaths.has(e.filePath))return;let n=!e.disableModelInvocation;this.togglingPaths=hT(this.togglingPaths,e.filePath),this.saveError=``;try{if(await this.skillsApi.toggle({cwd:t.cwd,filePath:e.filePath,disableModelInvocation:n},t.machineId),!this.isCurrentTarget(t))return;this.skills=this.skills.map(t=>t.filePath===e.filePath?{...t,disableModelInvocation:n}:t)}catch(e){this.isCurrentTarget(t)&&(this.saveError=bT(e))}finally{this.isCurrentTarget(t)&&(this.togglingPaths=_T(this.togglingPaths,e.filePath))}}async searchSkills(){let e=this.searchQuery.trim();if(e===``||this.searching)return;let t=this.machineId();this.searching=!0,this.searchError=``,this.searchResults=[];try{let n=await this.skillsApi.search({query:e},t);if(t!==this.machineId())return;this.searchResults=n.results,n.results.length===0&&(this.searchError=`No skills found`)}catch(e){t===this.machineId()&&(this.searchError=bT(e))}finally{t===this.machineId()&&(this.searching=!1)}}async installSkill(e){let t=this.target();if(t===void 0||this.installingPackage!==void 0)return;let n=this.installScope;this.installingPackage=e,this.installError=``;try{if(await this.skillsApi.install({cwd:t.cwd,package:e,scope:n},t.machineId),!this.isCurrentTarget(t))return;this.newlyInstalledKeys=hT(this.newlyInstalledKeys,pT(n,e)),await this.loadSkills()}catch(e){this.isCurrentTarget(t)&&(this.installError=bT(e))}finally{this.isCurrentTarget(t)&&(this.installingPackage=void 0)}}async checkForUpdates(e){let t=this.target();if(t===void 0)return;let n=(e===void 0?this.skills.filter(e=>e.install!==void 0):[e]).flatMap(e=>{let t=dT(e);return t===void 0?[]:[t]});if(n.length!==0){this.updateError=``,this.checkingUpdateKeys=gT(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!0);try{let n=e?.install,r=await this.skillsApi.check(n===void 0?{cwd:t.cwd}:{cwd:t.cwd,package:n.package,scope:n.scope},t.machineId);if(!this.isCurrentTarget(t))return;let i={...this.updateStatuses};for(let e of r.updates)i[`${e.scope}\0${e.package}`]=e;this.updateStatuses=i}catch(e){this.isCurrentTarget(t)&&(this.updateError=bT(e))}finally{this.isCurrentTarget(t)&&(this.checkingUpdateKeys=vT(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!1))}}}async updateInstalledSkill(e){let t=this.target(),n=e.install,r=dT(e);if(!(t===void 0||n===void 0||r===void 0||this.updatingKey!==void 0)){this.updatingKey=r,this.updateError=``;try{let e=await this.skillsApi.update({cwd:t.cwd,package:n.package,scope:n.scope},t.machineId);if(!this.isCurrentTarget(t)||(await this.loadSkills(),!this.isCurrentTarget(t)))return;let i=e.skill?.install?.versionHash;this.updateStatuses={...this.updateStatuses,[r]:{package:n.package,scope:n.scope,state:`up-to-date`,...i===void 0?{}:{currentVersion:i,latestVersion:i}}}}catch(e){this.isCurrentTarget(t)&&(this.updateError=bT(e))}finally{this.isCurrentTarget(t)&&(this.updatingKey=void 0)}}}selectSkill(e){this.selectedFilePath=e.filePath,this.addMode=!1,this.saveError=``,this.updateError=``}openAddMode(){this.addMode=!0,this.updateComplete.then(()=>{this.searchInput?.focus()})}selectedSkill(){return this.skills.find(e=>e.filePath===this.selectedFilePath)}skillGroups(){return[{label:`project / skills.sh`,matches:e=>oT(e)===`project`&&e.install?.skillsShUrl!==void 0},{label:`project`,matches:e=>oT(e)===`project`&&e.install?.skillsShUrl===void 0},{label:`global / skills.sh`,matches:e=>oT(e)===`global`&&e.install?.skillsShUrl!==void 0},{label:`global`,matches:e=>oT(e)===`global`&&e.install?.skillsShUrl===void 0},{label:`path`,matches:e=>oT(e)===`path`}].flatMap(e=>{let t=this.skills.filter(e.matches);return t.length===0?[]:[{label:e.label,skills:t}]})}isInstalled(e,t){return this.skills.some(n=>n.install?.scope===t&&n.install.package===e)||this.newlyInstalledKeys.has(pT(t,e))}target(){return this.cwd===``?void 0:{cwd:this.cwd,machineId:this.machineId()}}isCurrentTarget(e){return e.cwd===this.cwd&&e.machineId===this.machineId()}machineId(){return iT(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}resetForTargetChange(){this.loadRequestSequence+=1,this.skills=[],this.loading=!0,this.loadError=``,this.selectedFilePath=void 0,this.togglingPaths=new Set,this.saveError=``,this.addMode=!1,this.searchQuery=``,this.searchResults=[],this.searching=!1,this.searchError=``,this.installingPackage=void 0,this.installError=``,this.newlyInstalledKeys=new Set,this.installScope=`global`,this.updateStatuses={},this.checkingUpdateKeys=new Set,this.checkingAll=!1,this.updatingKey=void 0,this.updateError=``}static{this.styles=h`
3783
+ `}async loadSkills(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage skills.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.skillsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.skills=n.skills,this.selectedFilePath=sT(this.selectedFilePath,n.skills)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load skills: ${ST(n)}`)}finally{this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loading=!1)}}async toggleSkill(e){let t=this.target();if(t===void 0||this.togglingPaths.has(e.filePath))return;let n=!e.disableModelInvocation;this.togglingPaths=_T(this.togglingPaths,e.filePath),this.saveError=``;try{if(await this.skillsApi.toggle({cwd:t.cwd,filePath:e.filePath,disableModelInvocation:n},t.machineId),!this.isCurrentTarget(t))return;this.skills=this.skills.map(t=>t.filePath===e.filePath?{...t,disableModelInvocation:n}:t)}catch(e){this.isCurrentTarget(t)&&(this.saveError=ST(e))}finally{this.isCurrentTarget(t)&&(this.togglingPaths=yT(this.togglingPaths,e.filePath))}}async searchSkills(){let e=this.searchQuery.trim();if(e===``||this.searching)return;let t=this.machineId();this.searching=!0,this.searchError=``,this.searchResults=[];try{let n=await this.skillsApi.search({query:e},t);if(t!==this.machineId())return;this.searchResults=n.results,n.results.length===0&&(this.searchError=`No skills found`)}catch(e){t===this.machineId()&&(this.searchError=ST(e))}finally{t===this.machineId()&&(this.searching=!1)}}async installSkill(e){let t=this.target();if(t===void 0||this.installingPackage!==void 0)return;let n=this.installScope;this.installingPackage=e,this.installError=``;try{if(await this.skillsApi.install({cwd:t.cwd,package:e,scope:n},t.machineId),!this.isCurrentTarget(t))return;this.newlyInstalledKeys=_T(this.newlyInstalledKeys,hT(n,e)),await this.loadSkills()}catch(e){this.isCurrentTarget(t)&&(this.installError=ST(e))}finally{this.isCurrentTarget(t)&&(this.installingPackage=void 0)}}async checkForUpdates(e){let t=this.target();if(t===void 0)return;let n=(e===void 0?this.skills.filter(e=>e.install!==void 0):[e]).flatMap(e=>{let t=pT(e);return t===void 0?[]:[t]});if(n.length!==0){this.updateError=``,this.checkingUpdateKeys=vT(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!0);try{let n=e?.install,r=await this.skillsApi.check(n===void 0?{cwd:t.cwd}:{cwd:t.cwd,package:n.package,scope:n.scope},t.machineId);if(!this.isCurrentTarget(t))return;let i={...this.updateStatuses};for(let e of r.updates)i[`${e.scope}\0${e.package}`]=e;this.updateStatuses=i}catch(e){this.isCurrentTarget(t)&&(this.updateError=ST(e))}finally{this.isCurrentTarget(t)&&(this.checkingUpdateKeys=bT(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!1))}}}async updateInstalledSkill(e){let t=this.target(),n=e.install,r=pT(e);if(!(t===void 0||n===void 0||r===void 0||this.updatingKey!==void 0)){this.updatingKey=r,this.updateError=``;try{let e=await this.skillsApi.update({cwd:t.cwd,package:n.package,scope:n.scope},t.machineId);if(!this.isCurrentTarget(t)||(await this.loadSkills(),!this.isCurrentTarget(t)))return;let i=e.skill?.install?.versionHash;this.updateStatuses={...this.updateStatuses,[r]:{package:n.package,scope:n.scope,state:`up-to-date`,...i===void 0?{}:{currentVersion:i,latestVersion:i}}}}catch(e){this.isCurrentTarget(t)&&(this.updateError=ST(e))}finally{this.isCurrentTarget(t)&&(this.updatingKey=void 0)}}}selectSkill(e){this.selectedFilePath=e.filePath,this.addMode=!1,this.saveError=``,this.updateError=``}openAddMode(){this.addMode=!0,this.updateComplete.then(()=>{this.searchInput?.focus()})}selectedSkill(){return this.skills.find(e=>e.filePath===this.selectedFilePath)}skillGroups(){return[{label:`project / skills.sh`,matches:e=>cT(e)===`project`&&e.install?.skillsShUrl!==void 0},{label:`project`,matches:e=>cT(e)===`project`&&e.install?.skillsShUrl===void 0},{label:`global / skills.sh`,matches:e=>cT(e)===`global`&&e.install?.skillsShUrl!==void 0},{label:`global`,matches:e=>cT(e)===`global`&&e.install?.skillsShUrl===void 0},{label:`path`,matches:e=>cT(e)===`path`}].flatMap(e=>{let t=this.skills.filter(e.matches);return t.length===0?[]:[{label:e.label,skills:t}]})}isInstalled(e,t){return this.skills.some(n=>n.install?.scope===t&&n.install.package===e)||this.newlyInstalledKeys.has(hT(t,e))}target(){return this.cwd===``?void 0:{cwd:this.cwd,machineId:this.machineId()}}isCurrentTarget(e){return e.cwd===this.cwd&&e.machineId===this.machineId()}machineId(){return oT(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}resetForTargetChange(){this.loadRequestSequence+=1,this.skills=[],this.loading=!0,this.loadError=``,this.selectedFilePath=void 0,this.togglingPaths=new Set,this.saveError=``,this.addMode=!1,this.searchQuery=``,this.searchResults=[],this.searching=!1,this.searchError=``,this.installingPackage=void 0,this.installError=``,this.newlyInstalledKeys=new Set,this.installScope=`global`,this.updateStatuses={},this.checkingUpdateKeys=new Set,this.checkingAll=!1,this.updatingKey=void 0,this.updateError=``}static{this.styles=h`
3752
3784
  :host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
3753
3785
  .backdrop { position: absolute; inset: 0; display: grid; place-items: center; box-sizing: border-box; padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); background: var(--pi-overlay); }
3754
3786
  .dialog { width: min(860px, 100%); height: min(78dvh, 760px); max-height: 100%; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); }
@@ -3849,16 +3881,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3849
3881
  .scope-row { align-items: flex-start; flex-direction: column; gap: 6px; }
3850
3882
  .search-result { align-items: flex-start; }
3851
3883
  }
3852
- `}};B([x({attribute:!1})],J.prototype,`machine`,void 0),B([x({type:String})],J.prototype,`cwd`,void 0),B([x({attribute:!1})],J.prototype,`skillsApi`,void 0),B([x({attribute:!1})],J.prototype,`onClose`,void 0),B([S()],J.prototype,`skills`,void 0),B([S()],J.prototype,`loading`,void 0),B([S()],J.prototype,`loadError`,void 0),B([S()],J.prototype,`selectedFilePath`,void 0),B([S()],J.prototype,`togglingPaths`,void 0),B([S()],J.prototype,`saveError`,void 0),B([S()],J.prototype,`addMode`,void 0),B([S()],J.prototype,`searchQuery`,void 0),B([S()],J.prototype,`searchResults`,void 0),B([S()],J.prototype,`searching`,void 0),B([S()],J.prototype,`searchError`,void 0),B([S()],J.prototype,`installingPackage`,void 0),B([S()],J.prototype,`installError`,void 0),B([S()],J.prototype,`newlyInstalledKeys`,void 0),B([S()],J.prototype,`installScope`,void 0),B([S()],J.prototype,`updateStatuses`,void 0),B([S()],J.prototype,`checkingUpdateKeys`,void 0),B([S()],J.prototype,`checkingAll`,void 0),B([S()],J.prototype,`updatingKey`,void 0),B([S()],J.prototype,`updateError`,void 0),B([C(`#skill-search`)],J.prototype,`searchInput`,void 0),J=B([b(`skills-config-dialog`)],J);function iT(e){if(!xT(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function aT(e,t){return e!==void 0&&t.some(t=>t.filePath===e)?e:t[0]?.filePath}function oT(e){let t=e.sourceInfo.source,n=e.sourceInfo.scope;return n===`user`||t===`user`?`global`:n===`project`||t===`project`?`project`:`path`}function sT(e,t){return oT(e)===`project`&&e.filePath.startsWith(t)?`./${e.filePath.slice(t.length).replace(/^[/\\]/u,``)}`:cT(e.filePath)}function cT(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function lT(e){return e.replace(/^https?:\/\//u,``)}function uT(e){return e===void 0||e===``?`unknown`:e.slice(0,8)}function dT(e){return e.install===void 0?void 0:`${e.install.scope}\0${e.install.package}`}function fT(e,t){let n=dT(e);return n===void 0?void 0:t[n]}function pT(e,t){return`${e}\0${t}`}function mT(e){let t=e.lastIndexOf(`@`);return t<0?{repository:e,skill:void 0}:{repository:e.slice(0,t),skill:e.slice(t+1)}}function hT(e,t){return new Set([...e,t])}function gT(e,t){return new Set([...e,...t])}function _T(e,t){let n=new Set(e);return n.delete(t),n}function vT(e,t){let n=new Set(e);for(let e of t)n.delete(e);return n}function yT(e){let t=e.target;return t instanceof HTMLInputElement?t.value:``}function bT(e){return e instanceof Error?e.message:String(e)}function xT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ST(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function CT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}var Y=class extends y{constructor(...e){super(...e),this.cwd=``,this.pluginsApi=io,this.sessionsApi=co,this.loading=!0,this.loadError=``,this.addMode=!1,this.installSource=``,this.installScope=`global`,this.actionError=``,this.actionMessage=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadPlugins()}updated(e){let t=e.has(`machine`)&&jT(e.get(`machine`))!==this.machineId(),n=e.has(`cwd`)&&e.get(`cwd`)!==this.cwd;!t&&!n||(this.resetForTargetChange(),this.isConnected&&this.loadPlugins())}render(){let e=this.selectedPackage();return g`
3884
+ `}};B([x({attribute:!1})],q.prototype,`machine`,void 0),B([x({type:String})],q.prototype,`cwd`,void 0),B([x({attribute:!1})],q.prototype,`skillsApi`,void 0),B([x({attribute:!1})],q.prototype,`onClose`,void 0),B([S()],q.prototype,`skills`,void 0),B([S()],q.prototype,`loading`,void 0),B([S()],q.prototype,`loadError`,void 0),B([S()],q.prototype,`selectedFilePath`,void 0),B([S()],q.prototype,`togglingPaths`,void 0),B([S()],q.prototype,`saveError`,void 0),B([S()],q.prototype,`addMode`,void 0),B([S()],q.prototype,`searchQuery`,void 0),B([S()],q.prototype,`searchResults`,void 0),B([S()],q.prototype,`searching`,void 0),B([S()],q.prototype,`searchError`,void 0),B([S()],q.prototype,`installingPackage`,void 0),B([S()],q.prototype,`installError`,void 0),B([S()],q.prototype,`newlyInstalledKeys`,void 0),B([S()],q.prototype,`installScope`,void 0),B([S()],q.prototype,`updateStatuses`,void 0),B([S()],q.prototype,`checkingUpdateKeys`,void 0),B([S()],q.prototype,`checkingAll`,void 0),B([S()],q.prototype,`updatingKey`,void 0),B([S()],q.prototype,`updateError`,void 0),B([C(`#skill-search`)],q.prototype,`searchInput`,void 0),q=B([b(`skills-config-dialog`)],q);function oT(e){if(!CT(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function sT(e,t){return e!==void 0&&t.some(t=>t.filePath===e)?e:t[0]?.filePath}function cT(e){let t=e.sourceInfo.source,n=e.sourceInfo.scope;return n===`user`||t===`user`?`global`:n===`project`||t===`project`?`project`:`path`}function lT(e,t){return cT(e)===`project`&&e.filePath.startsWith(t)?`./${e.filePath.slice(t.length).replace(/^[/\\]/u,``)}`:uT(e.filePath)}function uT(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function dT(e){return e.replace(/^https?:\/\//u,``)}function fT(e){return e===void 0||e===``?`unknown`:e.slice(0,8)}function pT(e){return e.install===void 0?void 0:`${e.install.scope}\0${e.install.package}`}function mT(e,t){let n=pT(e);return n===void 0?void 0:t[n]}function hT(e,t){return`${e}\0${t}`}function gT(e){let t=e.lastIndexOf(`@`);return t<0?{repository:e,skill:void 0}:{repository:e.slice(0,t),skill:e.slice(t+1)}}function _T(e,t){return new Set([...e,t])}function vT(e,t){return new Set([...e,...t])}function yT(e,t){let n=new Set(e);return n.delete(t),n}function bT(e,t){let n=new Set(e);for(let e of t)n.delete(e);return n}function xT(e){let t=e.target;return t instanceof HTMLInputElement?t.value:``}function ST(e){return e instanceof Error?e.message:String(e)}function CT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function TT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}var J=class extends y{constructor(...e){super(...e),this.cwd=``,this.pluginsApi=io,this.sessionsApi=co,this.loading=!0,this.loadError=``,this.addMode=!1,this.installSource=``,this.installScope=`global`,this.actionError=``,this.actionMessage=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadPlugins()}updated(e){let t=e.has(`machine`)&&NT(e.get(`machine`))!==this.machineId(),n=e.has(`cwd`)&&e.get(`cwd`)!==this.cwd;!t&&!n||(this.resetForTargetChange(),this.isConnected&&this.loadPlugins())}render(){let e=this.selectedPackage();return g`
3853
3885
  <div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
3854
3886
  <section class="dialog" role="dialog" aria-modal="true" aria-labelledby="plugins-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3855
3887
  <header>
3856
3888
  <div class="title-block">
3857
3889
  <h1 id="plugins-dialog-title">Plugins</h1>
3858
- <span class="target"><code>${MT(this.cwd)}</code> on ${this.machineLabel()}</span>
3890
+ <span class="target"><code>${PT(this.cwd)}</code> on ${this.machineLabel()}</span>
3859
3891
  </div>
3860
3892
  <button class="icon-button" type="button" title="Close Plugins configuration" aria-label="Close Plugins configuration" @click=${()=>{this.close()}}>
3861
- ${RT()}
3893
+ ${BT()}
3862
3894
  </button>
3863
3895
  </header>
3864
3896
 
@@ -3884,20 +3916,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3884
3916
  </div>
3885
3917
  <div class="package-list-actions">
3886
3918
  <button class="add-plugin" type="button" aria-pressed=${String(this.addMode)} @click=${()=>{this.openAddMode()}}>
3887
- ${LT()} Add plugin
3919
+ ${zT()} Add plugin
3888
3920
  </button>
3889
3921
  </div>
3890
3922
  </aside>
3891
- `}renderPackageListItem(e){let t=wT(e),n=!this.addMode&&t===this.selectedKey;return g`
3923
+ `}renderPackageListItem(e){let t=ET(e),n=!this.addMode&&t===this.selectedKey;return g`
3892
3924
  <button class="package-row ${n?`selected`:``}" type="button" aria-pressed=${String(n)} @click=${()=>{this.selectPackage(e)}}>
3893
- <span class="package-indicator" style=${`background:${kT(e.status)}`} aria-hidden="true"></span>
3925
+ <span class="package-indicator" style=${`background:${jT(e.status)}`} aria-hidden="true"></span>
3894
3926
  <span class="package-copy">
3895
3927
  <strong>${e.source}</strong>
3896
- <small>${DT(e)}</small>
3897
- ${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${OT(e)}</small>`}
3928
+ <small>${kT(e)}</small>
3929
+ ${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${AT(e)}</small>`}
3898
3930
  </span>
3899
3931
  </button>
3900
- `}renderPackageDetail(e){let t=wT(e),n=this.busyKey?.endsWith(t)??!1,r=this.busyKey===`reload`,i=!e.disabled;return g`
3932
+ `}renderPackageDetail(e){let t=ET(e),n=this.busyKey?.endsWith(t)??!1,r=this.busyKey===`reload`,i=!e.disabled;return g`
3901
3933
  <div class="detail-content">
3902
3934
  <div class="detail-heading">
3903
3935
  <div class="package-title-row">
@@ -3929,12 +3961,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3929
3961
  </div>
3930
3962
 
3931
3963
  <dl class="metadata-grid">
3932
- <dt>Status</dt><dd style=${`color:${kT(e.status)}`}>${e.status}</dd>
3933
- <dt>Version</dt><dd><code>${OT(e)}</code></dd>
3964
+ <dt>Status</dt><dd style=${`color:${jT(e.status)}`}>${e.status}</dd>
3965
+ <dt>Version</dt><dd><code>${AT(e)}</code></dd>
3934
3966
  <dt>Package</dt><dd><code>${e.packageName??`Unknown`}</code></dd>
3935
- <dt>Resources</dt><dd>${DT(e)}</dd>
3936
- <dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:MT(e.installedPath)}</code></dd>
3937
- <dt>Workspace</dt><dd><code>${MT(this.cwd)}</code></dd>
3967
+ <dt>Resources</dt><dd>${kT(e)}</dd>
3968
+ <dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:PT(e.installedPath)}</code></dd>
3969
+ <dt>Workspace</dt><dd><code>${PT(this.cwd)}</code></dd>
3938
3970
  </dl>
3939
3971
 
3940
3972
  <section class="resource-section">
@@ -3963,7 +3995,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3963
3995
  <div class="detail-content add-panel">
3964
3996
  <div class="add-heading">
3965
3997
  <h2>Add Plugin</h2>
3966
- <code>${this.installScope===`project`?`${MT(this.cwd)}/.pi/agent/{npm,git}`:`~/.pi/agent/{npm,git}`}</code>
3998
+ <code>${this.installScope===`project`?`${PT(this.cwd)}/.pi/agent/{npm,git}`:`~/.pi/agent/{npm,git}`}</code>
3967
3999
  </div>
3968
4000
 
3969
4001
  <div class="field-stack">
@@ -3972,7 +4004,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3972
4004
  id="plugin-source"
3973
4005
  .value=${this.installSource}
3974
4006
  placeholder="npm:@scope/package"
3975
- @input=${e=>{this.installSource=PT(e)}}
4007
+ @input=${e=>{this.installSource=IT(e)}}
3976
4008
  @keydown=${t=>{t.key!==`Enter`||this.installSource.trim()===``||e||(t.preventDefault(),this.installPlugin())}}
3977
4009
  >
3978
4010
  </div>
@@ -3999,7 +4031,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3999
4031
  `}renderFooter(){let e=this.data,t=e?.diagnostics??[],n=this.busyKey!==void 0;return g`
4000
4032
  <footer>
4001
4033
  <div class="footer-summary">
4002
- ${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(NT).join(`
4034
+ ${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(FT).join(`
4003
4035
  `)}>
4004
4036
  ${String(t.length)} diagnostic${t.length===1?``:`s`}
4005
4037
  </span>`:e===void 0?null:g`<span>${String(e.totals.extensions)} ext · ${String(e.totals.skills)} skills · ${String(e.totals.prompts)} prompts · ${String(e.totals.themes)} themes</span>`}
@@ -4007,7 +4039,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4007
4039
  <button type="button" class="secondary" ?disabled=${this.loading||n} @click=${()=>{this.loadPlugins()}}>Refresh</button>
4008
4040
  <button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
4009
4041
  </footer>
4010
- `}async loadPlugins(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage plugins.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.pluginsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.data=n,this.addMode=n.packages.length===0||this.addMode,this.selectedKey=TT(this.selectedKey,n.packages)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load plugins: ${FT(n)}`)}finally{this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loading=!1)}}async runAction(e,t){let n=this.target();if(n===void 0||this.busyKey!==void 0)return;let r=wT(t);this.busyKey=`${e}:${r}`,this.actionError=``,this.actionMessage=``;try{let r=await this.pluginsApi.mutate({action:e,source:t.source,scope:t.scope,cwd:n.cwd},n.machineId);if(!this.isCurrentTarget(n))return;this.data=r,e===`remove`?(this.selectedKey=TT(void 0,r.packages),r.packages.length===0&&(this.addMode=!0),this.actionMessage=`Package removed.`):this.actionMessage=AT(e)}catch(e){this.isCurrentTarget(n)&&(this.actionError=FT(e))}finally{this.isCurrentTarget(n)&&(this.busyKey=void 0)}}async installPlugin(){let e=this.target(),t=this.installSource.trim();if(e===void 0||t===``||this.busyKey!==void 0)return;let n=this.installScope,r=`${n}\0${t}`;this.busyKey=`install:${r}`,this.actionError=``,this.actionMessage=``;try{let i=await this.pluginsApi.mutate({action:`install`,source:t,scope:n,cwd:e.cwd},e.machineId);if(!this.isCurrentTarget(e))return;this.data=i;let a=ET(i.packages,t,n);this.selectedKey=a===void 0?r:wT(a),this.addMode=!1,this.installSource=``,this.actionMessage=`Package installed.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=FT(t))}finally{this.isCurrentTarget(e)&&(this.busyKey=void 0)}}async reloadSession(){let e=this.target(),t=this.session;if(!(e===void 0||t===void 0||this.busyKey!==void 0)){this.busyKey=`reload`,this.actionError=``,this.actionMessage=``;try{let n=await this.sessionsApi.runCommand(t,`/reload`,e.machineId);if(n.type!==`done`)throw Error(n.type===`unsupported`?n.message:`Session runtime reload did not complete.`);if(!this.isCurrentTarget(e)||(await this.onReloaded?.(),await this.loadPlugins(),!this.isCurrentTarget(e)))return;this.actionMessage=`Session reloaded.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=FT(t))}finally{this.isCurrentTarget(e)&&(this.busyKey=void 0)}}}packageGroups(){let e=this.data?.packages??[];return[`project`,`global`].flatMap(t=>{let n=e.filter(e=>e.scope===t);return n.length===0?[]:[{scope:t,packages:n}]})}selectedPackage(){return(this.data?.packages??[]).find(e=>wT(e)===this.selectedKey)}selectPackage(e){this.selectedKey=wT(e),this.addMode=!1,this.actionError=``,this.actionMessage=``}openAddMode(){this.addMode=!0,this.actionError=``,this.actionMessage=``,this.updateComplete.then(()=>{this.pluginSourceInput?.focus()})}target(){return this.cwd===``?void 0:{cwd:this.cwd,machineId:this.machineId()}}isCurrentTarget(e){return e.cwd===this.cwd&&e.machineId===this.machineId()}machineId(){return jT(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}resetForTargetChange(){this.loadRequestSequence+=1,this.data=void 0,this.loading=!0,this.loadError=``,this.selectedKey=void 0,this.addMode=!1,this.installSource=``,this.installScope=`global`,this.busyKey=void 0,this.actionError=``,this.actionMessage=``}static{this.styles=h`
4042
+ `}async loadPlugins(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage plugins.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.pluginsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.data=n,this.addMode=n.packages.length===0||this.addMode,this.selectedKey=DT(this.selectedKey,n.packages)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load plugins: ${LT(n)}`)}finally{this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loading=!1)}}async runAction(e,t){let n=this.target();if(n===void 0||this.busyKey!==void 0)return;let r=ET(t);this.busyKey=`${e}:${r}`,this.actionError=``,this.actionMessage=``;try{let r=await this.pluginsApi.mutate({action:e,source:t.source,scope:t.scope,cwd:n.cwd},n.machineId);if(!this.isCurrentTarget(n))return;this.data=r,e===`remove`?(this.selectedKey=DT(void 0,r.packages),r.packages.length===0&&(this.addMode=!0),this.actionMessage=`Package removed.`):this.actionMessage=MT(e)}catch(e){this.isCurrentTarget(n)&&(this.actionError=LT(e))}finally{this.isCurrentTarget(n)&&(this.busyKey=void 0)}}async installPlugin(){let e=this.target(),t=this.installSource.trim();if(e===void 0||t===``||this.busyKey!==void 0)return;let n=this.installScope,r=`${n}\0${t}`;this.busyKey=`install:${r}`,this.actionError=``,this.actionMessage=``;try{let i=await this.pluginsApi.mutate({action:`install`,source:t,scope:n,cwd:e.cwd},e.machineId);if(!this.isCurrentTarget(e))return;this.data=i;let a=OT(i.packages,t,n);this.selectedKey=a===void 0?r:ET(a),this.addMode=!1,this.installSource=``,this.actionMessage=`Package installed.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=LT(t))}finally{this.isCurrentTarget(e)&&(this.busyKey=void 0)}}async reloadSession(){let e=this.target(),t=this.session;if(!(e===void 0||t===void 0||this.busyKey!==void 0)){this.busyKey=`reload`,this.actionError=``,this.actionMessage=``;try{let n=await this.sessionsApi.runCommand(t,`/reload`,e.machineId);if(n.type!==`done`)throw Error(n.type===`unsupported`?n.message:`Session runtime reload did not complete.`);if(!this.isCurrentTarget(e)||(await this.onReloaded?.(),await this.loadPlugins(),!this.isCurrentTarget(e)))return;this.actionMessage=`Session reloaded.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=LT(t))}finally{this.isCurrentTarget(e)&&(this.busyKey=void 0)}}}packageGroups(){let e=this.data?.packages??[];return[`project`,`global`].flatMap(t=>{let n=e.filter(e=>e.scope===t);return n.length===0?[]:[{scope:t,packages:n}]})}selectedPackage(){return(this.data?.packages??[]).find(e=>ET(e)===this.selectedKey)}selectPackage(e){this.selectedKey=ET(e),this.addMode=!1,this.actionError=``,this.actionMessage=``}openAddMode(){this.addMode=!0,this.actionError=``,this.actionMessage=``,this.updateComplete.then(()=>{this.pluginSourceInput?.focus()})}target(){return this.cwd===``?void 0:{cwd:this.cwd,machineId:this.machineId()}}isCurrentTarget(e){return e.cwd===this.cwd&&e.machineId===this.machineId()}machineId(){return NT(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}resetForTargetChange(){this.loadRequestSequence+=1,this.data=void 0,this.loading=!0,this.loadError=``,this.selectedKey=void 0,this.addMode=!1,this.installSource=``,this.installScope=`global`,this.busyKey=void 0,this.actionError=``,this.actionMessage=``}static{this.styles=h`
4011
4043
  :host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
4012
4044
  .backdrop { position: absolute; inset: 0; display: grid; box-sizing: border-box; place-items: center; padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); background: var(--pi-overlay); }
4013
4045
  .dialog { display: flex; width: min(860px, 100%); height: min(78dvh, 760px); max-height: 100%; flex-direction: column; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); }
@@ -4109,7 +4141,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4109
4141
  .package-actions { width: 100%; }
4110
4142
  .metadata-grid { grid-template-columns: 96px minmax(0, 1fr); }
4111
4143
  }
4112
- `}};B([x({attribute:!1})],Y.prototype,`machine`,void 0),B([x({type:String})],Y.prototype,`cwd`,void 0),B([x({attribute:!1})],Y.prototype,`session`,void 0),B([x({attribute:!1})],Y.prototype,`pluginsApi`,void 0),B([x({attribute:!1})],Y.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],Y.prototype,`onClose`,void 0),B([x({attribute:!1})],Y.prototype,`onReloaded`,void 0),B([S()],Y.prototype,`data`,void 0),B([S()],Y.prototype,`loading`,void 0),B([S()],Y.prototype,`loadError`,void 0),B([S()],Y.prototype,`selectedKey`,void 0),B([S()],Y.prototype,`addMode`,void 0),B([S()],Y.prototype,`installSource`,void 0),B([S()],Y.prototype,`installScope`,void 0),B([S()],Y.prototype,`busyKey`,void 0),B([S()],Y.prototype,`actionError`,void 0),B([S()],Y.prototype,`actionMessage`,void 0),B([C(`#plugin-source`)],Y.prototype,`pluginSourceInput`,void 0),Y=B([b(`plugins-config-dialog`)],Y);function wT(e){return`${e.scope}\0${e.source}`}function TT(e,t){return e!==void 0&&t.some(t=>wT(t)===e)?e:t[0]===void 0?void 0:wT(t[0])}function ET(e,t,n){let r=t.trim(),i=r.startsWith(`npm:`)?r.slice(4):r;return e.find(e=>e.scope===n&&e.source===r)??e.find(e=>e.scope===n&&e.source===`npm:${i}`)??e.find(e=>e.scope===n&&e.installedPath===r)??e.find(e=>e.scope===n&&e.source.endsWith(r))}function DT(e){if(e.disabled)return`Disabled`;let t=[e.counts.extensions===0?``:`${String(e.counts.extensions)} ext`,e.counts.skills===0?``:`${String(e.counts.skills)} skills`,e.counts.prompts===0?``:`${String(e.counts.prompts)} prompts`,e.counts.themes===0?``:`${String(e.counts.themes)} themes`].filter(e=>e!==``);return t.length===0?`No resources`:t.join(` · `)}function OT(e){let t=[e.version===void 0?void 0:`installed ${e.version}`,e.configuredVersion===void 0?void 0:`configured ${e.configuredVersion}`].filter(e=>e!==void 0);return t.length===0?`Unknown`:t.join(` · `)}function kT(e){return e===`loaded`?`var(--pi-accent)`:e===`installed`?`#d97706`:e===`disabled`?`var(--pi-muted)`:`var(--pi-danger)`}function AT(e){switch(e){case`install`:return`Package installed.`;case`update`:return`Package updated.`;case`disable`:return`Package disabled.`;case`enable`:return`Package enabled.`}}function jT(e){if(!IT(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function MT(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function NT(e){return`${e.type}: ${e.source===void 0?``:`${e.source}: `}${e.message}`}function PT(e){return e.target instanceof HTMLInputElement?e.target.value:``}function FT(e){return e instanceof Error?e.message:String(e)}function IT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function LT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function RT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}var zT=class extends y{constructor(...e){super(...e),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(){let e=++this.requestId;this.loading=!0;try{let t=await L.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`){let t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return g`
4144
+ `}};B([x({attribute:!1})],J.prototype,`machine`,void 0),B([x({type:String})],J.prototype,`cwd`,void 0),B([x({attribute:!1})],J.prototype,`session`,void 0),B([x({attribute:!1})],J.prototype,`pluginsApi`,void 0),B([x({attribute:!1})],J.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],J.prototype,`onClose`,void 0),B([x({attribute:!1})],J.prototype,`onReloaded`,void 0),B([S()],J.prototype,`data`,void 0),B([S()],J.prototype,`loading`,void 0),B([S()],J.prototype,`loadError`,void 0),B([S()],J.prototype,`selectedKey`,void 0),B([S()],J.prototype,`addMode`,void 0),B([S()],J.prototype,`installSource`,void 0),B([S()],J.prototype,`installScope`,void 0),B([S()],J.prototype,`busyKey`,void 0),B([S()],J.prototype,`actionError`,void 0),B([S()],J.prototype,`actionMessage`,void 0),B([C(`#plugin-source`)],J.prototype,`pluginSourceInput`,void 0),J=B([b(`plugins-config-dialog`)],J);function ET(e){return`${e.scope}\0${e.source}`}function DT(e,t){return e!==void 0&&t.some(t=>ET(t)===e)?e:t[0]===void 0?void 0:ET(t[0])}function OT(e,t,n){let r=t.trim(),i=r.startsWith(`npm:`)?r.slice(4):r;return e.find(e=>e.scope===n&&e.source===r)??e.find(e=>e.scope===n&&e.source===`npm:${i}`)??e.find(e=>e.scope===n&&e.installedPath===r)??e.find(e=>e.scope===n&&e.source.endsWith(r))}function kT(e){if(e.disabled)return`Disabled`;let t=[e.counts.extensions===0?``:`${String(e.counts.extensions)} ext`,e.counts.skills===0?``:`${String(e.counts.skills)} skills`,e.counts.prompts===0?``:`${String(e.counts.prompts)} prompts`,e.counts.themes===0?``:`${String(e.counts.themes)} themes`].filter(e=>e!==``);return t.length===0?`No resources`:t.join(` · `)}function AT(e){let t=[e.version===void 0?void 0:`installed ${e.version}`,e.configuredVersion===void 0?void 0:`configured ${e.configuredVersion}`].filter(e=>e!==void 0);return t.length===0?`Unknown`:t.join(` · `)}function jT(e){return e===`loaded`?`var(--pi-accent)`:e===`installed`?`#d97706`:e===`disabled`?`var(--pi-muted)`:`var(--pi-danger)`}function MT(e){switch(e){case`install`:return`Package installed.`;case`update`:return`Package updated.`;case`disable`:return`Package disabled.`;case`enable`:return`Package enabled.`}}function NT(e){if(!RT(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function PT(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function FT(e){return`${e.type}: ${e.source===void 0?``:`${e.source}: `}${e.message}`}function IT(e){return e.target instanceof HTMLInputElement?e.target.value:``}function LT(e){return e instanceof Error?e.message:String(e)}function RT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function BT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}var VT=class extends y{constructor(...e){super(...e),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(){let e=++this.requestId;this.loading=!0;try{let t=await L.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`){let t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return g`
4113
4145
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
4114
4146
  <section @click=${e=>{e.stopPropagation()}}>
4115
4147
  <header>
@@ -4159,7 +4191,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4159
4191
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
4160
4192
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
4161
4193
  button:disabled { opacity: .5; cursor: not-allowed; }
4162
- `}};B([x({attribute:!1})],zT.prototype,`onSubmit`,void 0),B([x({attribute:!1})],zT.prototype,`onCancel`,void 0),B([x()],zT.prototype,`machineId`,void 0),B([S()],zT.prototype,`path`,void 0),B([S()],zT.prototype,`createMissing`,void 0),B([S()],zT.prototype,`suggestions`,void 0),B([S()],zT.prototype,`selected`,void 0),B([S()],zT.prototype,`loading`,void 0),B([C(`input`)],zT.prototype,`pathInput`,void 0),zT=B([b(`project-dialog`)],zT);var BT=class extends y{constructor(...e){super(...e),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;let t=e.target.value,n=VT(t);(!this.nameEdited||this.name.trim()===``||this.name===this.previousSuggestedName)&&(this.name=n),this.previousSuggestedName=n,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`&&HT(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){let e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){let e=this.url.trim(),t=this.name.trim();if(e===``||t===``||HT(e)!==void 0)return;let n=this.token.trim();return{name:t,baseUrl:e,...n===``?{}:{token:n}}}render(){let e=this.url.trim()!==``,t=e?HT(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
4194
+ `}};B([x({attribute:!1})],VT.prototype,`onSubmit`,void 0),B([x({attribute:!1})],VT.prototype,`onCancel`,void 0),B([x()],VT.prototype,`machineId`,void 0),B([S()],VT.prototype,`path`,void 0),B([S()],VT.prototype,`createMissing`,void 0),B([S()],VT.prototype,`suggestions`,void 0),B([S()],VT.prototype,`selected`,void 0),B([S()],VT.prototype,`loading`,void 0),B([C(`input`)],VT.prototype,`pathInput`,void 0),VT=B([b(`project-dialog`)],VT);var HT=class extends y{constructor(...e){super(...e),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;let t=e.target.value,n=UT(t);(!this.nameEdited||this.name.trim()===``||this.name===this.previousSuggestedName)&&(this.name=n),this.previousSuggestedName=n,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`&&WT(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){let e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){let e=this.url.trim(),t=this.name.trim();if(e===``||t===``||WT(e)!==void 0)return;let n=this.token.trim();return{name:t,baseUrl:e,...n===``?{}:{token:n}}}render(){let e=this.url.trim()!==``,t=e?WT(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
4163
4195
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
4164
4196
  <section @click=${e=>{e.stopPropagation()}}>
4165
4197
  <form @submit=${e=>{this.handleSubmit(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>
@@ -4214,7 +4246,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4214
4246
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
4215
4247
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
4216
4248
  button:disabled { opacity: .5; cursor: not-allowed; }
4217
- `}};B([x({attribute:!1})],BT.prototype,`onSubmit`,void 0),B([x({attribute:!1})],BT.prototype,`onCancel`,void 0),B([x()],BT.prototype,`error`,void 0),B([S()],BT.prototype,`url`,void 0),B([S()],BT.prototype,`name`,void 0),B([S()],BT.prototype,`token`,void 0),B([S()],BT.prototype,`submitting`,void 0),B([C(`input[name='baseUrl']`)],BT.prototype,`urlInput`,void 0),B([C(`input[name='name']`)],BT.prototype,`nameInput`,void 0),BT=B([b(`machine-dialog`)],BT);function VT(e){let t=e.trim();if(t===``)return``;let n=UT(t)??UT(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):WT(t)}function HT(e){let t=e.trim();if(t===``)return`Remote PI WEBUI URL is required.`;let n;try{n=new URL(t)}catch{return`Enter a valid URL including http:// or https://.`}if(n.protocol!==`http:`&&n.protocol!==`https:`)return`Use an http:// or https:// URL.`;if(n.username!==``||n.password!==``)return`Do not include credentials in the machine URL.`;if(n.search!==``||n.hash!==``)return`Do not include a query string or fragment.`}function UT(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function WT(e){let t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,``),n=t.slice(t.lastIndexOf(`@`)+1).split(/[/?#]/u)[0]??``;return n.startsWith(`[`)&&n.includes(`]`)?n.slice(1,n.indexOf(`]`)):n.replace(/:\d+$/u,``)}var GT={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function KT(e){return e.tone??GT[e.type]}var qT=class extends y{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
4249
+ `}};B([x({attribute:!1})],HT.prototype,`onSubmit`,void 0),B([x({attribute:!1})],HT.prototype,`onCancel`,void 0),B([x()],HT.prototype,`error`,void 0),B([S()],HT.prototype,`url`,void 0),B([S()],HT.prototype,`name`,void 0),B([S()],HT.prototype,`token`,void 0),B([S()],HT.prototype,`submitting`,void 0),B([C(`input[name='baseUrl']`)],HT.prototype,`urlInput`,void 0),B([C(`input[name='name']`)],HT.prototype,`nameInput`,void 0),HT=B([b(`machine-dialog`)],HT);function UT(e){let t=e.trim();if(t===``)return``;let n=GT(t)??GT(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):KT(t)}function WT(e){let t=e.trim();if(t===``)return`Remote PI WEBUI URL is required.`;let n;try{n=new URL(t)}catch{return`Enter a valid URL including http:// or https://.`}if(n.protocol!==`http:`&&n.protocol!==`https:`)return`Use an http:// or https:// URL.`;if(n.username!==``||n.password!==``)return`Do not include credentials in the machine URL.`;if(n.search!==``||n.hash!==``)return`Do not include a query string or fragment.`}function GT(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function KT(e){let t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,``),n=t.slice(t.lastIndexOf(`@`)+1).split(/[/?#]/u)[0]??``;return n.startsWith(`[`)&&n.includes(`]`)?n.slice(1,n.indexOf(`]`)):n.replace(/:\d+$/u,``)}var qT={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function JT(e){return e.tone??qT[e.type]}var YT=class extends y{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
4218
4250
  <section class="panel" aria-label=${this.heading||`Settings panel`}>
4219
4251
  <header class="section-heading">
4220
4252
  <div class="heading-copy">
@@ -4237,7 +4269,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4237
4269
  <div class="notice-stack" aria-label="Settings notices">
4238
4270
  ${this.notices.map(e=>this.renderNotice(e))}
4239
4271
  </div>
4240
- `}renderNotice(e){let t=KT(e),n=e.role??JT(t),r=e.title;return g`
4272
+ `}renderNotice(e){let t=JT(e),n=e.role??XT(t),r=e.title;return g`
4241
4273
  <article class=${`notice ${t}`} role=${n}>
4242
4274
  ${r===void 0||r===``?v:g`<strong class="notice-title">${r}</strong>`}
4243
4275
  <div class="notice-content">${e.content}</div>
@@ -4270,13 +4302,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4270
4302
  .section-heading { display: grid; gap: 12px; }
4271
4303
  .heading-actions { justify-self: start; }
4272
4304
  }
4273
- `}};B([x()],qT.prototype,`heading`,void 0),B([x({attribute:!1})],qT.prototype,`description`,void 0),B([x()],qT.prototype,`actionLabel`,void 0),B([x()],qT.prototype,`actionTitle`,void 0),B([x({type:Boolean})],qT.prototype,`actionDisabled`,void 0),B([x({attribute:!1})],qT.prototype,`notices`,void 0),B([x({attribute:!1})],qT.prototype,`onAction`,void 0),qT=B([b(`settings-panel-frame`)],qT);function JT(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function YT(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function XT(){return{allowedPathsText:``,uploadDefaultFolder:``}}function ZT(){return{command:``,dir:``}}function QT(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(`
4274
- `):``}}function $T(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
4275
- `)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function eE(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function tE(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function nE(e,t){let n=tE(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function rE(e,t={}){let n=aE(t),r=e.host.trim(),i=e.port.trim();if(r!==``&&(n.host=r),i!==``){let e=Number(i);if(!Number.isInteger(e)||e<1||e>65535)throw Error(`Port must be an integer from 1 to 65535.`);n.port=e}return n.allowedHosts=e.allowedHostsMode===`all`||oE(e.allowedHostsText),n}function iE(e){let t=sE(e.allowedPathsText),n=cE(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function aE(e){return{...e.shortcuts===void 0?{}:{shortcuts:e.shortcuts},...e.plugins===void 0?{}:{plugins:e.plugins},...e.pathAccess===void 0?{}:{pathAccess:e.pathAccess},...e.uploads===void 0?{}:{uploads:e.uploads},...e.maxUploadBytes===void 0?{}:{maxUploadBytes:e.maxUploadBytes},...e.spawnSessions===void 0?{}:{spawnSessions:e.spawnSessions},...e.subsessions===void 0?{}:{subsessions:e.subsessions},...e.agent===void 0?{}:{agent:e.agent}}}function oE(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function sE(e){let t=e.split(`
4276
- `).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!lE(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function cE(e){let t=e.trim();if(t===``)return``;if(uE(t))throw Error(`Upload default folder must be workspace-relative.`);let n=t.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(n.length===0)return``;if(n.some(e=>e===`..`))throw Error(`Upload default folder must not contain path traversal.`);return n.join(`/`)}function lE(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function uE(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function dE(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var fE=class extends y{constructor(...e){super(...e),this.loading=!1,this.machineLoading=!1,this.saving=!1,this.error=``,this.machineError=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.gatewayDraft=YT(),this.machineDraft=XT(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=QT(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=$T(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
4305
+ `}};B([x()],YT.prototype,`heading`,void 0),B([x({attribute:!1})],YT.prototype,`description`,void 0),B([x()],YT.prototype,`actionLabel`,void 0),B([x()],YT.prototype,`actionTitle`,void 0),B([x({type:Boolean})],YT.prototype,`actionDisabled`,void 0),B([x({attribute:!1})],YT.prototype,`notices`,void 0),B([x({attribute:!1})],YT.prototype,`onAction`,void 0),YT=B([b(`settings-panel-frame`)],YT);function XT(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function ZT(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function QT(){return{allowedPathsText:``,uploadDefaultFolder:``}}function $T(){return{command:``,dir:``}}function eE(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(`
4306
+ `):``}}function tE(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
4307
+ `)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function nE(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function rE(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function iE(e,t){let n=rE(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function aE(e,t={}){let n=sE(t),r=e.host.trim(),i=e.port.trim();if(r!==``&&(n.host=r),i!==``){let e=Number(i);if(!Number.isInteger(e)||e<1||e>65535)throw Error(`Port must be an integer from 1 to 65535.`);n.port=e}return n.allowedHosts=e.allowedHostsMode===`all`||cE(e.allowedHostsText),n}function oE(e){let t=lE(e.allowedPathsText),n=uE(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function sE(e){return{...e.shortcuts===void 0?{}:{shortcuts:e.shortcuts},...e.plugins===void 0?{}:{plugins:e.plugins},...e.pathAccess===void 0?{}:{pathAccess:e.pathAccess},...e.uploads===void 0?{}:{uploads:e.uploads},...e.maxUploadBytes===void 0?{}:{maxUploadBytes:e.maxUploadBytes},...e.spawnSessions===void 0?{}:{spawnSessions:e.spawnSessions},...e.subsessions===void 0?{}:{subsessions:e.subsessions},...e.agent===void 0?{}:{agent:e.agent}}}function cE(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function lE(e){let t=e.split(`
4308
+ `).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!dE(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function uE(e){let t=e.trim();if(t===``)return``;if(fE(t))throw Error(`Upload default folder must be workspace-relative.`);let n=t.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(n.length===0)return``;if(n.some(e=>e===`..`))throw Error(`Upload default folder must not contain path traversal.`);return n.join(`/`)}function dE(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function fE(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function pE(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var Y=class extends y{constructor(...e){super(...e),this.loading=!1,this.machineLoading=!1,this.saving=!1,this.error=``,this.machineError=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.gatewayDraft=ZT(),this.machineDraft=QT(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=eE(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=tE(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
4277
4309
  <settings-panel-frame
4278
4310
  heading="General configuration"
4279
- .description=${dE(this.targetLabel)}
4311
+ .description=${pE(this.targetLabel)}
4280
4312
  actionLabel="Reload"
4281
4313
  .actionDisabled=${this.loading||this.machineLoading}
4282
4314
  .notices=${this.panelNotices()}
@@ -4305,7 +4337,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4305
4337
  <span>Host</span>
4306
4338
  ${this.renderOverrideBadge(`host`)}
4307
4339
  </span>
4308
- <input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:hE(e)})}}>
4340
+ <input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:gE(e)})}}>
4309
4341
  <small>Address the web server should bind to. Leave empty to use PI WEBUI's default.</small>
4310
4342
  </label>
4311
4343
 
@@ -4314,7 +4346,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4314
4346
  <span>Port</span>
4315
4347
  ${this.renderOverrideBadge(`port`)}
4316
4348
  </span>
4317
- <input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:hE(e)})}}>
4349
+ <input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:gE(e)})}}>
4318
4350
  <small>TCP port from 1 to 65535. Leave empty to use PI WEBUI's default.</small>
4319
4351
  </label>
4320
4352
 
@@ -4323,11 +4355,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4323
4355
  <span>Allowed hosts</span>
4324
4356
  ${this.renderOverrideBadge(`allowedHosts`)}
4325
4357
  </span>
4326
- <select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:gE(e)===`all`?`all`:`list`})}}>
4358
+ <select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:_E(e)===`all`?`all`:`list`})}}>
4327
4359
  <option value="list">Only listed hosts</option>
4328
4360
  <option value="all">Allow every host</option>
4329
4361
  </select>
4330
- <textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode===`all`} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${e=>{this.updateGatewayDraft({allowedHostsText:_E(e)})}}></textarea>
4362
+ <textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode===`all`} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${e=>{this.updateGatewayDraft({allowedHostsText:vE(e)})}}></textarea>
4331
4363
  <small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
4332
4364
  </div>
4333
4365
 
@@ -4357,7 +4389,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4357
4389
  <span class="field-heading">
4358
4390
  <span>External filesystem roots</span>
4359
4391
  </span>
4360
- <textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:_E(e)})}}></textarea>
4392
+ <textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:vE(e)})}}></textarea>
4361
4393
  <small>Allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace on ${this.targetLabel}. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
4362
4394
  </label>
4363
4395
 
@@ -4365,7 +4397,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4365
4397
  <span class="field-heading">
4366
4398
  <span>Default upload folder</span>
4367
4399
  </span>
4368
- <input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${xo} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:hE(e)})}}>
4400
+ <input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${xo} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:gE(e)})}}>
4369
4401
  <small>Workspace-relative folder for manual file uploads on ${this.targetLabel}. Leave empty to use PI WEBUI's default <code>${xo}</code>.</small>
4370
4402
  </label>
4371
4403
 
@@ -4383,18 +4415,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4383
4415
  <dl>
4384
4416
  <div><dt>Host</dt><dd>${e.host??g`<span class="muted">127.0.0.1 default</span>`}</dd></div>
4385
4417
  <div><dt>Port</dt><dd>${e.port??g`<span class="muted">8808 default</span>`}</dd></div>
4386
- <div><dt>Allowed hosts</dt><dd>${pE(e.allowedHosts)}</dd></div>
4418
+ <div><dt>Allowed hosts</dt><dd>${mE(e.allowedHosts)}</dd></div>
4387
4419
  </dl>
4388
4420
  </section>
4389
4421
  `}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
4390
4422
  <section class="effective-card" aria-label="Effective selected machine file access and upload summary">
4391
4423
  <h3>Effective selected-machine settings</h3>
4392
4424
  <dl>
4393
- <div><dt>External roots</dt><dd>${mE(e.pathAccess?.allowedPaths)}</dd></div>
4425
+ <div><dt>External roots</dt><dd>${hE(e.pathAccess?.allowedPaths)}</dd></div>
4394
4426
  <div><dt>Upload folder</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">${`.pi-webui/uploads`} default</span>`}</dd></div>
4395
4427
  </dl>
4396
4428
  </section>
4397
- `}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(rE(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=vE(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(iE(this.machineDraft))}catch(e){this.machineLocalError=vE(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
4429
+ `}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(aE(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=yE(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(oE(this.machineDraft))}catch(e){this.machineLocalError=yE(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
4398
4430
  :host { display: block; }
4399
4431
  .card-heading { display: grid; gap: 6px; min-width: 0; }
4400
4432
  h3, p { margin: 0; }
@@ -4433,10 +4465,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4433
4465
  @media (max-width: 760px) {
4434
4466
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
4435
4467
  }
4436
- `}};B([x({attribute:!1})],fE.prototype,`configResponse`,void 0),B([x({attribute:!1})],fE.prototype,`machineConfigResponse`,void 0),B([x({type:Boolean})],fE.prototype,`loading`,void 0),B([x({type:Boolean})],fE.prototype,`machineLoading`,void 0),B([x({type:Boolean})],fE.prototype,`saving`,void 0),B([x()],fE.prototype,`error`,void 0),B([x()],fE.prototype,`machineError`,void 0),B([x()],fE.prototype,`savedMessage`,void 0),B([x()],fE.prototype,`targetLabel`,void 0),B([x({attribute:!1})],fE.prototype,`onReload`,void 0),B([x({attribute:!1})],fE.prototype,`onReloadMachine`,void 0),B([x({attribute:!1})],fE.prototype,`onSave`,void 0),B([x({attribute:!1})],fE.prototype,`onSaveMachineConfig`,void 0),B([S()],fE.prototype,`gatewayDraft`,void 0),B([S()],fE.prototype,`machineDraft`,void 0),B([S()],fE.prototype,`gatewayLocalError`,void 0),B([S()],fE.prototype,`machineLocalError`,void 0),fE=B([b(`settings-general-panel`)],fE);function pE(e){return e===!0?`Any host`:Array.isArray(e)?e.length===0?g`<span class="muted">None listed</span>`:e.join(`, `):g`<span class="muted">Unset</span>`}function mE(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function hE(e){return e.target instanceof HTMLInputElement?e.target.value:``}function gE(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function _E(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function vE(e){return e instanceof Error?e.message:String(e)}function yE(e){return{spawnSessions:e}}function bE(e){return{subsessions:e}}function xE(e,t){let n=e?.effectiveConfig.agent;if(n?.command===void 0||n.dir===void 0||t===void 0)return`unavailable`;let r=[`PI_WEBUI_AGENT_SESSION_DIR`,...jt(n.command)?[`PI_CODING_AGENT_SESSION_DIR`]:[]];return n.command===t.command&&n.dir===t.dir&&wE(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function SE(e,t){return e?.agentDirSource===`pi-webui`?!0:e?.agentDirSource===`pi-compatibility`?jt(t.trim()||`pi`):e?.agentDir===!0}function CE(e,t){let n={...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions,agentCommand:t.envOverrides.agentCommand,agentDir:t.envOverrides.agentDir,agentSessionDir:t.envOverrides.agentSessionDir};return t.envOverrides.agentDirSource===void 0?delete n.agentDirSource:n.agentDirSource=t.envOverrides.agentDirSource,{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:n}}function wE(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var TE=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`,this.agentProfileSupport={state:`supported`},this.agentDraft=ZT(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=ZT(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||nE(this.agentDraft,this.configResponse.config))&&(this.agentDraft=eE(this.configResponse.config),this.agentDraftDirty=!1,this.agentLocalError=``)}}render(){let e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,n=e?.effectiveConfig.spawnSessions!==!1,r=e?.envOverrides.subsessions===!0,i=e?.effectiveConfig.subsessions===!0&&n,a=e?.envOverrides.agentCommand===!0,o=this.agentProfileSupport.state===`supported`,s=a?e.effectiveConfig.agent?.command??this.agentDraft.command:this.agentDraft.command,c=SE(e?.envOverrides,s),l=e?.envOverrides.agentDir===!0,u=e?.effectiveConfig.agent,d=xE(e,this.activeAgentProfile);return g`
4468
+ `}};B([x({attribute:!1})],Y.prototype,`configResponse`,void 0),B([x({attribute:!1})],Y.prototype,`machineConfigResponse`,void 0),B([x({type:Boolean})],Y.prototype,`loading`,void 0),B([x({type:Boolean})],Y.prototype,`machineLoading`,void 0),B([x({type:Boolean})],Y.prototype,`saving`,void 0),B([x()],Y.prototype,`error`,void 0),B([x()],Y.prototype,`machineError`,void 0),B([x()],Y.prototype,`savedMessage`,void 0),B([x()],Y.prototype,`targetLabel`,void 0),B([x({attribute:!1})],Y.prototype,`onReload`,void 0),B([x({attribute:!1})],Y.prototype,`onReloadMachine`,void 0),B([x({attribute:!1})],Y.prototype,`onSave`,void 0),B([x({attribute:!1})],Y.prototype,`onSaveMachineConfig`,void 0),B([S()],Y.prototype,`gatewayDraft`,void 0),B([S()],Y.prototype,`machineDraft`,void 0),B([S()],Y.prototype,`gatewayLocalError`,void 0),B([S()],Y.prototype,`machineLocalError`,void 0),Y=B([b(`settings-general-panel`)],Y);function mE(e){return e===!0?`Any host`:Array.isArray(e)?e.length===0?g`<span class="muted">None listed</span>`:e.join(`, `):g`<span class="muted">Unset</span>`}function hE(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function gE(e){return e.target instanceof HTMLInputElement?e.target.value:``}function _E(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function vE(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function yE(e){return e instanceof Error?e.message:String(e)}function bE(e){return{spawnSessions:e}}function xE(e){return{subsessions:e}}function SE(e,t){let n=e?.effectiveConfig.agent;if(n?.command===void 0||n.dir===void 0||t===void 0)return`unavailable`;let r=[`PI_WEBUI_AGENT_SESSION_DIR`,...jt(n.command)?[`PI_CODING_AGENT_SESSION_DIR`]:[]];return n.command===t.command&&n.dir===t.dir&&TE(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function CE(e,t){return e?.agentDirSource===`pi-webui`?!0:e?.agentDirSource===`pi-compatibility`?jt(t.trim()||`pi`):e?.agentDir===!0}function wE(e,t){let n={...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions,agentCommand:t.envOverrides.agentCommand,agentDir:t.envOverrides.agentDir,agentSessionDir:t.envOverrides.agentSessionDir};return t.envOverrides.agentDirSource===void 0?delete n.agentDirSource:n.agentDirSource=t.envOverrides.agentDirSource,{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:n}}function TE(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var EE=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`,this.agentProfileSupport={state:`supported`},this.agentDraft=$T(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=$T(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||iE(this.agentDraft,this.configResponse.config))&&(this.agentDraft=nE(this.configResponse.config),this.agentDraftDirty=!1,this.agentLocalError=``)}}render(){let e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,n=e?.effectiveConfig.spawnSessions!==!1,r=e?.envOverrides.subsessions===!0,i=e?.effectiveConfig.subsessions===!0&&n,a=e?.envOverrides.agentCommand===!0,o=this.agentProfileSupport.state===`supported`,s=a?e.effectiveConfig.agent?.command??this.agentDraft.command:this.agentDraft.command,c=CE(e?.envOverrides,s),l=e?.envOverrides.agentDir===!0,u=e?.effectiveConfig.agent,d=SE(e,this.activeAgentProfile);return g`
4437
4469
  <settings-panel-frame
4438
4470
  heading="Session daemon"
4439
- .description=${kE(this.targetLabel)}
4471
+ .description=${AE(this.targetLabel)}
4440
4472
  actionLabel="Reload"
4441
4473
  .actionDisabled=${this.loading}
4442
4474
  .notices=${this.panelNotices(e)}
@@ -4462,7 +4494,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4462
4494
  .value=${this.agentDraft.command}
4463
4495
  placeholder="pi"
4464
4496
  ?disabled=${this.loading||this.saving||!o||a}
4465
- @input=${e=>{this.updateAgentDraft({command:DE(e)})}}
4497
+ @input=${e=>{this.updateAgentDraft({command:OE(e)})}}
4466
4498
  >
4467
4499
  <small>Set the Pi-compatible companion CLI used for doctor and update checks. The embedded session runtime remains PI WEBUI's bundled Pi SDK.</small>
4468
4500
  </label>
@@ -4479,7 +4511,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4479
4511
  .value=${this.agentDraft.dir}
4480
4512
  placeholder="~/.pi/agent or ~/agent-profiles/work"
4481
4513
  ?disabled=${this.loading||this.saving||!o||c}
4482
- @input=${e=>{this.updateAgentDraft({dir:DE(e)})}}
4514
+ @input=${e=>{this.updateAgentDraft({dir:OE(e)})}}
4483
4515
  >
4484
4516
  <small>Choose the Pi-compatible auth, models, settings, and sessions PI WEBUI reads. An alternate command and its required state directory are saved together.</small>
4485
4517
  </label>
@@ -4527,14 +4559,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4527
4559
  <div><dt>Desired state</dt><dd>${u?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
4528
4560
  <div><dt>Active command</dt><dd>${this.activeAgentProfile?.command??g`<span class="muted">Unavailable</span>`}</dd></div>
4529
4561
  <div><dt>Active state</dt><dd>${this.activeAgentProfile?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
4530
- <div><dt>Profile status</dt><dd>${EE(d)}</dd></div>
4562
+ <div><dt>Profile status</dt><dd>${DE(d)}</dd></div>
4531
4563
  <div><dt>Spawn sessions</dt><dd>${n?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
4532
4564
  <div><dt>Subsessions</dt><dd>${i?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
4533
4565
  </dl>
4534
4566
  </section>
4535
4567
  `}
4536
4568
  </settings-panel-frame>
4537
- `}panelNotices(e){return AE(e,{error:this.agentLocalError||this.error,savedMessage:this.savedMessage,activeProfile:this.activeAgentProfile,targetLabel:this.targetLabel,profileEditingSupported:this.agentProfileSupport.state===`supported`})}renderUnavailableConfigState(){return g`<div class="loading-card">${this.loading?`Loading configuration…`:`Configuration is unavailable. Reload to try again.`}</div>`}async saveAgentProfile(e){e.preventDefault(),this.agentLocalError=``;try{await this.onSave?.(tE(this.agentDraft))}catch(e){this.agentLocalError=OE(e)}}updateAgentDraft(e){this.agentDraft={...this.agentDraft,...e},this.agentDraftDirty=!0,this.agentLocalError=``}async toggleSpawnSessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(yE(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(bE(t))}static{this.styles=h`
4569
+ `}panelNotices(e){return jE(e,{error:this.agentLocalError||this.error,savedMessage:this.savedMessage,activeProfile:this.activeAgentProfile,targetLabel:this.targetLabel,profileEditingSupported:this.agentProfileSupport.state===`supported`})}renderUnavailableConfigState(){return g`<div class="loading-card">${this.loading?`Loading configuration…`:`Configuration is unavailable. Reload to try again.`}</div>`}async saveAgentProfile(e){e.preventDefault(),this.agentLocalError=``;try{await this.onSave?.(rE(this.agentDraft))}catch(e){this.agentLocalError=kE(e)}}updateAgentDraft(e){this.agentDraft={...this.agentDraft,...e},this.agentDraftDirty=!0,this.agentLocalError=``}async toggleSpawnSessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(bE(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(xE(t))}static{this.styles=h`
4538
4570
  :host { display: block; }
4539
4571
  h3 { margin: 0; font-size: 13px; line-height: 1.3; }
4540
4572
  button, input { font: inherit; }
@@ -4580,10 +4612,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4580
4612
  @media (max-width: 760px) {
4581
4613
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
4582
4614
  }
4583
- `}};B([x({attribute:!1})],TE.prototype,`configResponse`,void 0),B([x({type:Boolean})],TE.prototype,`loading`,void 0),B([x({type:Boolean})],TE.prototype,`saving`,void 0),B([x()],TE.prototype,`error`,void 0),B([x()],TE.prototype,`savedMessage`,void 0),B([x()],TE.prototype,`targetLabel`,void 0),B([x({attribute:!1})],TE.prototype,`activeAgentProfile`,void 0),B([x({attribute:!1})],TE.prototype,`agentProfileSupport`,void 0),B([x({attribute:!1})],TE.prototype,`onReload`,void 0),B([x({attribute:!1})],TE.prototype,`onSave`,void 0),B([S()],TE.prototype,`agentDraft`,void 0),B([S()],TE.prototype,`agentDraftDirty`,void 0),B([S()],TE.prototype,`agentLocalError`,void 0),TE=B([b(`settings-sessiond-panel`)],TE);function EE(e){return e===`active`?`Active`:e===`restart-required`?`Restart required`:g`<span class="muted">Unavailable</span>`}function DE(e){return e.target instanceof HTMLInputElement?e.target.value:``}function OE(e){return e instanceof Error?e.message:String(e)}function kE(e){return`Select the Pi-compatible agent profile and companion CLI for ${e}. Changes are saved immediately but only take effect after the session daemon on that machine restarts.`}function AE(e,t){let n=[];t.error!==``&&n.push({type:`error`,content:t.error}),t.savedMessage!==``&&n.push({type:`success`,content:t.savedMessage});let r=xE(e,t.activeProfile);return r===`restart-required`?n.push({type:`warning`,title:`Pi-compatible agent profile restart required on ${t.targetLabel}`,content:g`The desired profile differs from the active session-daemon profile. Run <code>pi-webui restart</code> on that machine (or restart its session daemon service) to apply the command and state directory together.`}):e!==void 0&&r===`unavailable`&&t.profileEditingSupported&&n.push({type:`info`,title:`Active Pi-compatible agent profile unavailable on ${t.targetLabel}`,content:`PI WEBUI cannot compare the desired profile with the running session daemon. Reload after the daemon is available.`}),n}function jE(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function ME(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function NE(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.piPackagesManage)?{state:`supported`}:{state:`unsupported`,message:IE(e)}:{state:`unknown`}}function PE(e){return`${e.state}:${e.message??``}`}function FE(e){return e?.state===`unsupported`}function IE(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function LE(e){return e.kind===`local`}function RE(e){return e.trim()}function zE(e){if(RE(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function BE(e){return e.scope===`project`?`Project scope`:`User scope`}function VE(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEBUI process`}function HE(e){return e.installedPath??`Installed path not reported by Pi`}function UE(e){return e.scope===`user`}function WE(e){if(!UE(e))return`Project-scope Pi packages are listed for visibility, but PI WEBUI only updates user-scope Pi packages safely from this view.`}function GE(e){return e.length>0&&e.every(UE)}function KE(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!GE(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function qE(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function JE(e,t=jE(void 0)){return`Pi package ${e===`install`?`installed`:e===`remove`?`removed`:`updated`}${t.kind===`local`?``:` on ${t.name}`}. Type /reload in ${t.kind===`local`?`each idle PI WEBUI session`:`each idle PI WEBUI session on ${t.name}`} to rediscover Pi runtime resources: extensions, skills, prompt templates, themes, and context/system prompt files. Reload the browser page separately for ${t.kind===`local`?`PI WEBUI browser plugin changes`:`PI WEBUI browser plugin changes served by ${t.name}`}.`}function YE(e,t){let n=e.trim();return t.kind===`remote`?XE(n)?IE(t):n===`Remote machine timeout`?`Timed out while contacting ${t.name} for Pi package management. The package operation may still be running remotely; reload the package list before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for Pi package management. Check the machine connection and try again.`:n:n}function XE(e){return e===`Not Found`||/route\s+(GET|POST):?\/api\/pi-packages\b.*not found/iu.test(e)||/cannot\s+(GET|POST)\s+.*\/api\/pi-packages\b/iu.test(e)}var ZE=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.operationMessage=``,this.installSource=``,this.validationMessage=``}render(){let e=this.packagesResponse?.packages??[],t=this.packageTarget,n=ME(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
4615
+ `}};B([x({attribute:!1})],EE.prototype,`configResponse`,void 0),B([x({type:Boolean})],EE.prototype,`loading`,void 0),B([x({type:Boolean})],EE.prototype,`saving`,void 0),B([x()],EE.prototype,`error`,void 0),B([x()],EE.prototype,`savedMessage`,void 0),B([x()],EE.prototype,`targetLabel`,void 0),B([x({attribute:!1})],EE.prototype,`activeAgentProfile`,void 0),B([x({attribute:!1})],EE.prototype,`agentProfileSupport`,void 0),B([x({attribute:!1})],EE.prototype,`onReload`,void 0),B([x({attribute:!1})],EE.prototype,`onSave`,void 0),B([S()],EE.prototype,`agentDraft`,void 0),B([S()],EE.prototype,`agentDraftDirty`,void 0),B([S()],EE.prototype,`agentLocalError`,void 0),EE=B([b(`settings-sessiond-panel`)],EE);function DE(e){return e===`active`?`Active`:e===`restart-required`?`Restart required`:g`<span class="muted">Unavailable</span>`}function OE(e){return e.target instanceof HTMLInputElement?e.target.value:``}function kE(e){return e instanceof Error?e.message:String(e)}function AE(e){return`Select the Pi-compatible agent profile and companion CLI for ${e}. Changes are saved immediately but only take effect after the session daemon on that machine restarts.`}function jE(e,t){let n=[];t.error!==``&&n.push({type:`error`,content:t.error}),t.savedMessage!==``&&n.push({type:`success`,content:t.savedMessage});let r=SE(e,t.activeProfile);return r===`restart-required`?n.push({type:`warning`,title:`Pi-compatible agent profile restart required on ${t.targetLabel}`,content:g`The desired profile differs from the active session-daemon profile. Run <code>pi-webui restart</code> on that machine (or restart its session daemon service) to apply the command and state directory together.`}):e!==void 0&&r===`unavailable`&&t.profileEditingSupported&&n.push({type:`info`,title:`Active Pi-compatible agent profile unavailable on ${t.targetLabel}`,content:`PI WEBUI cannot compare the desired profile with the running session daemon. Reload after the daemon is available.`}),n}function ME(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function NE(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function PE(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.piPackagesManage)?{state:`supported`}:{state:`unsupported`,message:LE(e)}:{state:`unknown`}}function FE(e){return`${e.state}:${e.message??``}`}function IE(e){return e?.state===`unsupported`}function LE(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function RE(e){return e.kind===`local`}function zE(e){return e.trim()}function BE(e){if(zE(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function VE(e){return e.scope===`project`?`Project scope`:`User scope`}function HE(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEBUI process`}function UE(e){return e.installedPath??`Installed path not reported by Pi`}function WE(e){return e.scope===`user`}function GE(e){if(!WE(e))return`Project-scope Pi packages are listed for visibility, but PI WEBUI only updates user-scope Pi packages safely from this view.`}function KE(e){return e.length>0&&e.every(WE)}function qE(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!KE(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function JE(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function YE(e,t=ME(void 0)){return`Pi package ${e===`install`?`installed`:e===`remove`?`removed`:`updated`}${t.kind===`local`?``:` on ${t.name}`}. Type /reload in ${t.kind===`local`?`each idle PI WEBUI session`:`each idle PI WEBUI session on ${t.name}`} to rediscover Pi runtime resources: extensions, skills, prompt templates, themes, and context/system prompt files. Reload the browser page separately for ${t.kind===`local`?`PI WEBUI browser plugin changes`:`PI WEBUI browser plugin changes served by ${t.name}`}.`}function XE(e,t){let n=e.trim();return t.kind===`remote`?ZE(n)?LE(t):n===`Remote machine timeout`?`Timed out while contacting ${t.name} for Pi package management. The package operation may still be running remotely; reload the package list before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for Pi package management. Check the machine connection and try again.`:n:n}function ZE(e){return e===`Not Found`||/route\s+(GET|POST):?\/api\/pi-packages\b.*not found/iu.test(e)||/cannot\s+(GET|POST)\s+.*\/api\/pi-packages\b/iu.test(e)}var QE=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.operationMessage=``,this.installSource=``,this.validationMessage=``}render(){let e=this.packagesResponse?.packages??[],t=this.packageTarget,n=NE(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
4584
4616
  <settings-panel-frame
4585
4617
  heading="Pi packages"
4586
- .description=${QE(n)}
4618
+ .description=${$E(n)}
4587
4619
  actionLabel="Reload"
4588
4620
  actionTitle=${r?this.packageManagementUnavailableMessage(n):`Reload Pi packages from ${n}`}
4589
4621
  .actionDisabled=${this.loading||this.isOperating||r}
@@ -4600,12 +4632,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4600
4632
  <label for="package-source">Pi package source</label>
4601
4633
  <div class="install-row">
4602
4634
  <input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package, git URL, or local path" @input=${e=>{this.updateInstallSource(e)}}>
4603
- <button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${qE(this.operation,`install`)?`Installing…`:`Install`}</button>
4635
+ <button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${JE(this.operation,`install`)?`Installing…`:`Install`}</button>
4604
4636
  </div>
4605
4637
  ${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
4606
4638
  <small>Installs run on ${e} and use Pi's default package location, equivalent to <code>pi install &lt;source&gt;</code>. PI WEBUI does not ask you to choose an install location.</small>
4607
4639
  </form>
4608
- `}renderPackageList(e,t){let n=ME(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):KE(e),i=r!==void 0&&e.length>0;return g`
4640
+ `}renderPackageList(e,t){let n=NE(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):qE(e),i=r!==void 0&&e.length>0;return g`
4609
4641
  <section class="package-section" aria-label="Configured Pi packages">
4610
4642
  <div class="package-toolbar">
4611
4643
  <div>
@@ -4613,7 +4645,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4613
4645
  <p>This list comes from Pi's package manager settings on ${n}.</p>
4614
4646
  </div>
4615
4647
  <button class="secondary" title=${r??`Update all user-scope Pi packages`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
4616
- ${qE(this.operation,`update-all`)?`Updating…`:`Update all`}
4648
+ ${JE(this.operation,`update-all`)?`Updating…`:`Update all`}
4617
4649
  </button>
4618
4650
  </div>
4619
4651
  ${i?g`<div class="action-note">${r}</div>`:null}
@@ -4624,12 +4656,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4624
4656
  <div class="package-list">
4625
4657
  ${e.map(e=>this.renderPackage(e))}
4626
4658
  </div>
4627
- `}renderPackage(e){let t=ME(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):WE(e),i=n?this.packageManagementUnavailableMessage(t):`Remove this Pi package`,a=qE(this.operation,`update`,e.source),o=qE(this.operation,`remove`,e.source);return g`
4659
+ `}renderPackage(e){let t=NE(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):GE(e),i=n?this.packageManagementUnavailableMessage(t):`Remove this Pi package`,a=JE(this.operation,`update`,e.source),o=JE(this.operation,`remove`,e.source);return g`
4628
4660
  <article class=${`package-card${e.filtered?` filtered`:``}`}>
4629
4661
  <div class="package-main">
4630
4662
  <strong>${e.source}</strong>
4631
- <small>${BE(e)} · ${VE(e)}</small>
4632
- <small>Installed path: <code>${HE(e)}</code></small>
4663
+ <small>${VE(e)} · ${HE(e)}</small>
4664
+ <small>Installed path: <code>${UE(e)}</code></small>
4633
4665
  ${r===void 0?null:g`<small class="action-note">${r}</small>`}
4634
4666
  </div>
4635
4667
  <div class="package-actions">
@@ -4637,7 +4669,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4637
4669
  <button class="danger" title=${i} ?disabled=${this.isOperating||n} @click=${()=>{this.removePackage(e)}}>${o?`Removing…`:`Remove`}</button>
4638
4670
  </div>
4639
4671
  </article>
4640
- `}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=zE(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=RE(this.installSource);try{await this.onInstallPackage?.(n),this.installSource=``,this.validationMessage=``}catch{}}async removePackage(e){try{await this.onRemovePackage?.(e.source,e.scope)}catch{}}async updatePackage(e){try{await this.onUpdatePackage?.(e)}catch{}}get packageTarget(){return this.targetMachine??jE(void 0)}get packageManagementUnavailable(){return FE(this.managementSupport)}packageManagementUnavailableMessage(e){return this.managementSupport?.message??`Pi package management is not available on ${e}.`}get isOperating(){return this.operation!==void 0}static{this.styles=h`
4672
+ `}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=BE(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=zE(this.installSource);try{await this.onInstallPackage?.(n),this.installSource=``,this.validationMessage=``}catch{}}async removePackage(e){try{await this.onRemovePackage?.(e.source,e.scope)}catch{}}async updatePackage(e){try{await this.onUpdatePackage?.(e)}catch{}}get packageTarget(){return this.targetMachine??ME(void 0)}get packageManagementUnavailable(){return IE(this.managementSupport)}packageManagementUnavailableMessage(e){return this.managementSupport?.message??`Pi package management is not available on ${e}.`}get isOperating(){return this.operation!==void 0}static{this.styles=h`
4641
4673
  :host { display: block; }
4642
4674
  .package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
4643
4675
  .package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
@@ -4672,10 +4704,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4672
4704
  .package-actions { justify-self: start; flex-wrap: wrap; }
4673
4705
  .package-main strong, .package-main small { white-space: normal; }
4674
4706
  }
4675
- `}};B([x({attribute:!1})],ZE.prototype,`packagesResponse`,void 0),B([x({type:Boolean})],ZE.prototype,`loading`,void 0),B([x({attribute:!1})],ZE.prototype,`operation`,void 0),B([x({attribute:!1})],ZE.prototype,`targetMachine`,void 0),B([x({attribute:!1})],ZE.prototype,`managementSupport`,void 0),B([x()],ZE.prototype,`error`,void 0),B([x()],ZE.prototype,`operationMessage`,void 0),B([x({attribute:!1})],ZE.prototype,`onReload`,void 0),B([x({attribute:!1})],ZE.prototype,`onInstallPackage`,void 0),B([x({attribute:!1})],ZE.prototype,`onRemovePackage`,void 0),B([x({attribute:!1})],ZE.prototype,`onUpdatePackage`,void 0),B([S()],ZE.prototype,`installSource`,void 0),B([S()],ZE.prototype,`validationMessage`,void 0),ZE=B([b(`settings-packages-panel`)],ZE);function QE(e){return g`Managing Pi packages on <strong>${e}</strong>. Install, remove, and update packages managed by Pi on the selected machine. Pi packages can provide extensions, skills, prompt templates, themes, context/system prompt files, and PI WEBUI browser plugins.`}var $E=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}render(){let e=this.pluginsResponse?.plugins??[],t=this.pluginsResponse!==void 0;return g`
4707
+ `}};B([x({attribute:!1})],QE.prototype,`packagesResponse`,void 0),B([x({type:Boolean})],QE.prototype,`loading`,void 0),B([x({attribute:!1})],QE.prototype,`operation`,void 0),B([x({attribute:!1})],QE.prototype,`targetMachine`,void 0),B([x({attribute:!1})],QE.prototype,`managementSupport`,void 0),B([x()],QE.prototype,`error`,void 0),B([x()],QE.prototype,`operationMessage`,void 0),B([x({attribute:!1})],QE.prototype,`onReload`,void 0),B([x({attribute:!1})],QE.prototype,`onInstallPackage`,void 0),B([x({attribute:!1})],QE.prototype,`onRemovePackage`,void 0),B([x({attribute:!1})],QE.prototype,`onUpdatePackage`,void 0),B([S()],QE.prototype,`installSource`,void 0),B([S()],QE.prototype,`validationMessage`,void 0),QE=B([b(`settings-packages-panel`)],QE);function $E(e){return g`Managing Pi packages on <strong>${e}</strong>. Install, remove, and update packages managed by Pi on the selected machine. Pi packages can provide extensions, skills, prompt templates, themes, context/system prompt files, and PI WEBUI browser plugins.`}var eD=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}render(){let e=this.pluginsResponse?.plugins??[],t=this.pluginsResponse!==void 0;return g`
4676
4708
  <settings-panel-frame
4677
4709
  heading="PI WEBUI plugins"
4678
- .description=${eD(this.targetLabel)}
4710
+ .description=${tD(this.targetLabel)}
4679
4711
  actionLabel="Reload"
4680
4712
  actionTitle=${`Reload PI WEBUI plugins from ${this.targetLabel}`}
4681
4713
  .actionDisabled=${this.loading}
@@ -4721,10 +4753,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4721
4753
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
4722
4754
  .toggle { justify-self: start; }
4723
4755
  }
4724
- `}};B([x({attribute:!1})],$E.prototype,`pluginsResponse`,void 0),B([x({attribute:!1})],$E.prototype,`configResponse`,void 0),B([x({type:Boolean})],$E.prototype,`loading`,void 0),B([x({type:Boolean})],$E.prototype,`saving`,void 0),B([x()],$E.prototype,`error`,void 0),B([x()],$E.prototype,`savedMessage`,void 0),B([x()],$E.prototype,`targetLabel`,void 0),B([x({attribute:!1})],$E.prototype,`onReload`,void 0),B([x({attribute:!1})],$E.prototype,`onTogglePlugin`,void 0),$E=B([b(`settings-plugins-panel`)],$E);function eD(e){return g`Enable or disable discovered PI WEBUI browser plugins on <strong>${e}</strong>. This is separate from installing Pi packages. Reload the browser tab to apply plugin runtime changes.`}var tD={capture:!0},nD=[{value:`auto`,label:`Auto/default`,description:`Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line.`},{value:`send`,label:`Enter sends message`,description:`Enter sends the chat message; Shift+Enter adds a new line when supported.`},{value:`newline`,label:`Enter inserts new line`,description:`Enter adds a line break; Shift+Enter sends the chat message when supported.`}];function rD(){return g`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.`}var iD=class extends y{constructor(...e){super(...e),this.actions=[],this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.drafts={},this.localError=``,this.promptEnterPreference=xC(),this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{let t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key===`Escape`){this.stopRecording();return}let n=kf(e);if(n===void 0){this.localError=`Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.`;return}if(t.tokens.length===0&&!Af(n)){this.localError=`Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.`;return}let r=[...t.tokens,n];this.localError=``,this.drafts={[t.actionId]:r.join(` `)},this.recording={actionId:t.actionId,tokens:r},this.armRecordingTimer()}}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.drafts={},this.localError=``,this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){let e=cD(this.actions),t=this.shortcutResolutions();return g`
4756
+ `}};B([x({attribute:!1})],eD.prototype,`pluginsResponse`,void 0),B([x({attribute:!1})],eD.prototype,`configResponse`,void 0),B([x({type:Boolean})],eD.prototype,`loading`,void 0),B([x({type:Boolean})],eD.prototype,`saving`,void 0),B([x()],eD.prototype,`error`,void 0),B([x()],eD.prototype,`savedMessage`,void 0),B([x()],eD.prototype,`targetLabel`,void 0),B([x({attribute:!1})],eD.prototype,`onReload`,void 0),B([x({attribute:!1})],eD.prototype,`onTogglePlugin`,void 0),eD=B([b(`settings-plugins-panel`)],eD);function tD(e){return g`Enable or disable discovered PI WEBUI browser plugins on <strong>${e}</strong>. This is separate from installing Pi packages. Reload the browser tab to apply plugin runtime changes.`}var nD={capture:!0},rD=[{value:`auto`,label:`Auto/default`,description:`Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line.`},{value:`send`,label:`Enter sends message`,description:`Enter sends the chat message; Shift+Enter adds a new line when supported.`},{value:`newline`,label:`Enter inserts new line`,description:`Enter adds a line break; Shift+Enter sends the chat message when supported.`}];function iD(){return g`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.`}var aD=class extends y{constructor(...e){super(...e),this.actions=[],this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.drafts={},this.localError=``,this.promptEnterPreference=CC(),this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{let t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key===`Escape`){this.stopRecording();return}let n=kf(e);if(n===void 0){this.localError=`Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.`;return}if(t.tokens.length===0&&!Af(n)){this.localError=`Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.`;return}let r=[...t.tokens,n];this.localError=``,this.drafts={[t.actionId]:r.join(` `)},this.recording={actionId:t.actionId,tokens:r},this.armRecordingTimer()}}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.drafts={},this.localError=``,this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){let e=lD(this.actions),t=this.shortcutResolutions();return g`
4725
4757
  <settings-panel-frame
4726
4758
  heading="Keyboard shortcuts"
4727
- .description=${rD()}
4759
+ .description=${iD()}
4728
4760
  actionLabel="Reload"
4729
4761
  .actionDisabled=${this.loading}
4730
4762
  .notices=${this.panelNotices()}
@@ -4755,7 +4787,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4755
4787
  <p>Choose what Enter does in this browser. Shift+Enter does the opposite when supported; automatic touch-keyboard capitalization is ignored to avoid accidental sends.</p>
4756
4788
  </div>
4757
4789
  <div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
4758
- ${nD.map(e=>g`
4790
+ ${rD.map(e=>g`
4759
4791
  <label class="prompt-enter-option">
4760
4792
  <input
4761
4793
  type="radio"
@@ -4772,8 +4804,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4772
4804
  `)}
4773
4805
  </div>
4774
4806
  </section>
4775
- `}updatePromptEnterPreference(e){this.promptEnterPreference=e,SC(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=uD(e.id,n),i=pD(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Ef(a),s=o?.ok===!0?o.shortcut:fD(e,n),c=r!==void 0,l=this.drafts[e.id]!==void 0,u=l&&a.trim()!==``?`custom`:i,d=this.recordingHint(e.id),f=sD(t);return g`
4776
- <article class=${aD(t)}>
4807
+ `}updatePromptEnterPreference(e){this.promptEnterPreference=e,wC(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=dD(e.id,n),i=mD(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Ef(a),s=o?.ok===!0?o.shortcut:pD(e,n),c=r!==void 0,l=this.drafts[e.id]!==void 0,u=l&&a.trim()!==``?`custom`:i,d=this.recordingHint(e.id),f=cD(t);return g`
4808
+ <article class=${oD(t)}>
4777
4809
  <div class="shortcut-main">
4778
4810
  <strong>${e.title}</strong>
4779
4811
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
@@ -4783,8 +4815,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4783
4815
  <div class="shortcut-editor">
4784
4816
  <div class="shortcut-status">
4785
4817
  ${s!==void 0&&s!==``?g`<kbd>${Of(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`Disabled`:`Unassigned`}</span>`}
4786
- <small class=${u}>${mD(u)}${l?` · Unsaved`:``}</small>
4787
- ${f===void 0?null:g`<small class=${oD(t)}>${f}</small>`}
4818
+ <small class=${u}>${hD(u)}${l?` · Unsaved`:``}</small>
4819
+ ${f===void 0?null:g`<small class=${sD(t)}>${f}</small>`}
4788
4820
  </div>
4789
4821
  <label class="shortcut-input-label">
4790
4822
  <span>Shortcut</span>
@@ -4797,7 +4829,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4797
4829
  autocapitalize="off"
4798
4830
  spellcheck="false"
4799
4831
  ?disabled=${this.saving}
4800
- @input=${t=>{this.updateDraft(e.id,hD(t))}}
4832
+ @input=${t=>{this.updateDraft(e.id,gD(t))}}
4801
4833
  >
4802
4834
  </label>
4803
4835
  ${d===``?null:g`<small class="recording-hint">${d}</small>`}
@@ -4809,7 +4841,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4809
4841
  </div>
4810
4842
  </div>
4811
4843
  </article>
4812
- `}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=uD(e.id,this.configResponse?.config.shortcuts);return n===null?``:n??e.shortcut??``}recordingHint(e){let t=this.recording;return t?.actionId===e?t.tokens.length===0?`Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.`:`Recording: ${Of(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();let t=Ef(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e.id,t.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){let n={...this.configResponse?.config??{}},r=n.shortcuts??{},i=t===void 0?dD(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Tf(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){let e={...this.configResponse?.config.shortcuts??{}};for(let[t,n]of Object.entries(this.drafts)){let r=n.trim();if(r===``)continue;let i=Ef(r);i.ok&&(e[t]=i.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(let 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()},Sf)}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,tD),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,tD),!1)}static{this.styles=h`
4844
+ `}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=dD(e.id,this.configResponse?.config.shortcuts);return n===null?``:n??e.shortcut??``}recordingHint(e){let t=this.recording;return t?.actionId===e?t.tokens.length===0?`Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.`:`Recording: ${Of(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();let t=Ef(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e.id,t.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){let n={...this.configResponse?.config??{}},r=n.shortcuts??{},i=t===void 0?fD(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Tf(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){let e={...this.configResponse?.config.shortcuts??{}};for(let[t,n]of Object.entries(this.drafts)){let r=n.trim();if(r===``)continue;let i=Ef(r);i.ok&&(e[t]=i.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(let 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()},Sf)}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,nD),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,nD),!1)}static{this.styles=h`
4813
4845
  :host { display: block; }
4814
4846
  h3, p { margin: 0; }
4815
4847
  h3 { font-size: 13px; line-height: 1.3; }
@@ -4865,7 +4897,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4865
4897
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
4866
4898
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
4867
4899
  }
4868
- `}};B([x({attribute:!1})],iD.prototype,`actions`,void 0),B([x({attribute:!1})],iD.prototype,`configResponse`,void 0),B([x({type:Boolean})],iD.prototype,`loading`,void 0),B([x({type:Boolean})],iD.prototype,`saving`,void 0),B([x()],iD.prototype,`error`,void 0),B([x()],iD.prototype,`savedMessage`,void 0),B([x({attribute:!1})],iD.prototype,`onReload`,void 0),B([x({attribute:!1})],iD.prototype,`onSave`,void 0),B([S()],iD.prototype,`drafts`,void 0),B([S()],iD.prototype,`localError`,void 0),B([S()],iD.prototype,`promptEnterPreference`,void 0),B([S()],iD.prototype,`recording`,void 0),iD=B([b(`settings-shortcuts-panel`)],iD);function aD(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function oD(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function sD(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??`another action`}`;let t=e.shadows.length;if(t===0)return;let n=e.shadows.slice(0,2).map(e=>e.action.title).join(`, `),r=t>2?`, +${String(t-2)} more`:``;return`Shadows ${String(t)} ${t===1?`action`:`actions`}: ${n}${r}`}function cD(e){let t=new Map;for(let n of[...e].sort(lD)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function lD(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function uD(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function dD(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function fD(e,t){let n=uD(e.id,t);if(n!==null)return n??e.shortcut}function pD(e,t){let n=uD(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function mD(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function hD(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function gD(e){let[t,n]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),r={error:``},i=[];return t.status===`fulfilled`?r.config=t.value:i.push(`config: ${vD(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEBUI plugins: ${vD(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function _D(e,t,n){if(FE(n))return{error:n.message??`Pi package management is not available on ${ME(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${ME(e)}: ${YE(vD(t),e)}`}}}function vD(e){return e instanceof Error?e.message:String(e)}function yD(e,t){return{...e,config:bD(e.config,t.config),effectiveConfig:bD(e.effectiveConfig,t.effectiveConfig)}}function bD(e,t){return{...e,...t.pathAccess===void 0?{}:{pathAccess:t.pathAccess},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes}}}function xD(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function SD(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function CD(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.selectedMachineSettings)?{state:`supported`}:{state:`unsupported`,message:OD(e)}:{state:`unknown`}}function wD(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.agentProfileConfig)?{state:`supported`}:{state:`unsupported`,message:`Pi-compatible agent profile settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}:{state:`unknown`,message:`Pi-compatible agent profile support could not be verified on ${e.name}. Reload machine status before changing the profile.`}}function TD(e){return`${e.state}:${e.message??``}`}function ED(e){return e?.state===`unsupported`}function DD(e){return e?.state===`supported`}function OD(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}function kD(e,t){let n=e.trim();return t.kind===`remote`?AD(n)?OD(t):n===`Remote machine timeout`?`Timed out while contacting ${t.name} for selected-machine settings. The operation may still be running remotely; reload before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for selected-machine settings. Check the machine connection and try again.`:n:n}function AD(e){return e===`Not Found`||/route\s+(GET|PUT):?\/api\/(config|plugins)\b.*not found/iu.test(e)||/cannot\s+(GET|PUT)\s+.*\/api\/(config|plugins)\b/iu.test(e)}function jD(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function MD(e,t){return{...e,config:ND(e.config,t.config),effectiveConfig:ND(e.effectiveConfig,t.effectiveConfig)}}function ND(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var X=class extends y{constructor(...e){super(...e),this.section=`general`,this.actions=[],this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){let t=this.settingsTarget();if(e.has(`machine`)&&xD(e.get(`machine`)).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t);return}e.has(`machineRuntime`)&&(this.selectedMachineSettingsSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t)),this.packageManagementSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return g`
4900
+ `}};B([x({attribute:!1})],aD.prototype,`actions`,void 0),B([x({attribute:!1})],aD.prototype,`configResponse`,void 0),B([x({type:Boolean})],aD.prototype,`loading`,void 0),B([x({type:Boolean})],aD.prototype,`saving`,void 0),B([x()],aD.prototype,`error`,void 0),B([x()],aD.prototype,`savedMessage`,void 0),B([x({attribute:!1})],aD.prototype,`onReload`,void 0),B([x({attribute:!1})],aD.prototype,`onSave`,void 0),B([S()],aD.prototype,`drafts`,void 0),B([S()],aD.prototype,`localError`,void 0),B([S()],aD.prototype,`promptEnterPreference`,void 0),B([S()],aD.prototype,`recording`,void 0),aD=B([b(`settings-shortcuts-panel`)],aD);function oD(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function sD(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function cD(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??`another action`}`;let t=e.shadows.length;if(t===0)return;let n=e.shadows.slice(0,2).map(e=>e.action.title).join(`, `),r=t>2?`, +${String(t-2)} more`:``;return`Shadows ${String(t)} ${t===1?`action`:`actions`}: ${n}${r}`}function lD(e){let t=new Map;for(let n of[...e].sort(uD)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function uD(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function dD(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function fD(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function pD(e,t){let n=dD(e.id,t);if(n!==null)return n??e.shortcut}function mD(e,t){let n=dD(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function hD(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function gD(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function _D(e){let[t,n]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),r={error:``},i=[];return t.status===`fulfilled`?r.config=t.value:i.push(`config: ${yD(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEBUI plugins: ${yD(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function vD(e,t,n){if(IE(n))return{error:n.message??`Pi package management is not available on ${NE(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${NE(e)}: ${XE(yD(t),e)}`}}}function yD(e){return e instanceof Error?e.message:String(e)}function bD(e,t){return{...e,config:xD(e.config,t.config),effectiveConfig:xD(e.effectiveConfig,t.effectiveConfig)}}function xD(e,t){return{...e,...t.pathAccess===void 0?{}:{pathAccess:t.pathAccess},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes}}}function SD(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function CD(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function wD(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.selectedMachineSettings)?{state:`supported`}:{state:`unsupported`,message:kD(e)}:{state:`unknown`}}function TD(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.agentProfileConfig)?{state:`supported`}:{state:`unsupported`,message:`Pi-compatible agent profile settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}:{state:`unknown`,message:`Pi-compatible agent profile support could not be verified on ${e.name}. Reload machine status before changing the profile.`}}function ED(e){return`${e.state}:${e.message??``}`}function DD(e){return e?.state===`unsupported`}function OD(e){return e?.state===`supported`}function kD(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}function AD(e,t){let n=e.trim();return t.kind===`remote`?jD(n)?kD(t):n===`Remote machine timeout`?`Timed out while contacting ${t.name} for selected-machine settings. The operation may still be running remotely; reload before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for selected-machine settings. Check the machine connection and try again.`:n:n}function jD(e){return e===`Not Found`||/route\s+(GET|PUT):?\/api\/(config|plugins)\b.*not found/iu.test(e)||/cannot\s+(GET|PUT)\s+.*\/api\/(config|plugins)\b/iu.test(e)}function MD(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function ND(e,t){return{...e,config:PD(e.config,t.config),effectiveConfig:PD(e.effectiveConfig,t.effectiveConfig)}}function PD(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var X=class extends y{constructor(...e){super(...e),this.section=`general`,this.actions=[],this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){let t=this.settingsTarget();if(e.has(`machine`)&&SD(e.get(`machine`)).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t);return}e.has(`machineRuntime`)&&(this.selectedMachineSettingsSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t)),this.packageManagementSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return g`
4869
4901
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
4870
4902
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEBUI settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
4871
4903
  <header class="settings-header">
@@ -4896,7 +4928,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4896
4928
  .saving=${this.saving}
4897
4929
  .error=${this.sessiondError}
4898
4930
  .savedMessage=${this.savedMessage}
4899
- .targetLabel=${SD(this.settingsTarget())}
4931
+ .targetLabel=${CD(this.settingsTarget())}
4900
4932
  .activeAgentProfile=${this.machineRuntime?.components?.sessiond.activeAgentProfile}
4901
4933
  .agentProfileSupport=${this.agentProfileSettingsSupport()}
4902
4934
  .onReload=${()=>this.reloadSessiondState()}
@@ -4935,7 +4967,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4935
4967
  .saving=${this.saving}
4936
4968
  .error=${this.pluginError}
4937
4969
  .savedMessage=${this.savedMessage}
4938
- .targetLabel=${SD(this.settingsTarget())}
4970
+ .targetLabel=${CD(this.settingsTarget())}
4939
4971
  .onReload=${()=>this.loadPluginsForTarget()}
4940
4972
  .onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
4941
4973
  ></settings-plugins-panel>
@@ -4949,7 +4981,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4949
4981
  .error=${this.error}
4950
4982
  .machineError=${this.accessError}
4951
4983
  .savedMessage=${this.savedMessage}
4952
- .targetLabel=${SD(this.settingsTarget())}
4984
+ .targetLabel=${CD(this.settingsTarget())}
4953
4985
  .onReload=${()=>this.loadConfig()}
4954
4986
  .onReloadMachine=${()=>this.loadAccessConfigForTarget()}
4955
4987
  .onSave=${e=>this.saveConfig(e)}
@@ -4960,7 +4992,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4960
4992
  <strong>${t}</strong>
4961
4993
  <small>${n}</small>
4962
4994
  </button>
4963
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await gD({loadConfig:()=>qa.config(),loadPlugins:()=>Ja.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(ED(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${SD(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await qa.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${SD(e)}: ${kD(PD(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(ED(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${SD(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await qa.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${SD(e)}: ${kD(PD(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(ED(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${SD(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([qa.config(e.id),Ja.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${kD(PD(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${kD(PD(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${SD(e)}: ${i.join(`; `)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await _D(e,e=>to.packages(e),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(ED(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${SD(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${SD(n)}. Reload before changing plugin enablement.`;return}let i=jD(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await qa.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=MD(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEBUI plugin config on ${SD(n)}: ${kD(PD(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await qa.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${PD(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(ED(n)){this.accessError=n.message??`Selected-machine settings are not available on ${SD(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await qa.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=yD(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${SD(t)}: ${kD(PD(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(ED(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${SD(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!DD(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${SD(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await qa.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=CE(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${SD(t)}: ${kD(PD(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>to.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>to.remove(e,t,n.id))}async updatePiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:`update-all`}:{kind:`update`,source:e},`update Pi packages`,t,()=>to.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(FE(i))throw this.packageError=i.message??`Pi package management is not available on ${ME(n)}.`,Error(this.packageError);if(this.saving)throw Error(`A settings operation is already running.`);let a=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(a,n))return;this.packagesResponse={packages:e.packages};let t=LE(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=JE(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${ME(n)}: ${YE(PD(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Ja.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${PD(e)}`}}async refreshPluginsForTarget(e){try{let t=await Ja.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${SD(e)}: ${kD(PD(t),e)}`}}settingsTarget(){return xD(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return CD(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return wD(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=CD(t,e),r=this.selectedMachineSettingsSupport(t);return TD(n)!==TD(r)}packageManagementSupport(e=this.packageTarget()){return NE(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=NE(t,e),r=this.packageManagementSupport(t);return PE(n)===PE(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}showSavedMessage(){this.savedMessage=`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?.())}static{this.styles=h`
4995
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await _D({loadConfig:()=>qa.config(),loadPlugins:()=>Ja.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(DD(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${CD(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await qa.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${CD(e)}: ${AD(FD(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(DD(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${CD(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await qa.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${CD(e)}: ${AD(FD(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(DD(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${CD(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([qa.config(e.id),Ja.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${AD(FD(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${AD(FD(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${CD(e)}: ${i.join(`; `)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await vD(e,e=>to.packages(e),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(DD(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${CD(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${CD(n)}. Reload before changing plugin enablement.`;return}let i=MD(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await qa.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=ND(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEBUI plugin config on ${CD(n)}: ${AD(FD(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await qa.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${FD(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(DD(n)){this.accessError=n.message??`Selected-machine settings are not available on ${CD(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await qa.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=bD(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${CD(t)}: ${AD(FD(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(DD(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${CD(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!OD(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${CD(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await qa.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=wE(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${CD(t)}: ${AD(FD(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>to.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>to.remove(e,t,n.id))}async updatePiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:`update-all`}:{kind:`update`,source:e},`update Pi packages`,t,()=>to.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(IE(i))throw this.packageError=i.message??`Pi package management is not available on ${NE(n)}.`,Error(this.packageError);if(this.saving)throw Error(`A settings operation is already running.`);let a=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(a,n))return;this.packagesResponse={packages:e.packages};let t=RE(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=YE(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${NE(n)}: ${XE(FD(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Ja.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${FD(e)}`}}async refreshPluginsForTarget(e){try{let t=await Ja.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${CD(e)}: ${AD(FD(t),e)}`}}settingsTarget(){return SD(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return wD(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return TD(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=wD(t,e),r=this.selectedMachineSettingsSupport(t);return ED(n)!==ED(r)}packageManagementSupport(e=this.packageTarget()){return PE(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=PE(t,e),r=this.packageManagementSupport(t);return FE(n)===FE(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}showSavedMessage(){this.savedMessage=`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?.())}static{this.styles=h`
4964
4996
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
4965
4997
  .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; }
4966
4998
  .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; }
@@ -4987,7 +5019,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4987
5019
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
4988
5020
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
4989
5021
  }
4990
- `}};B([x({attribute:!1})],X.prototype,`section`,void 0),B([x({attribute:!1})],X.prototype,`actions`,void 0),B([x({attribute:!1})],X.prototype,`machine`,void 0),B([x({attribute:!1})],X.prototype,`machineRuntime`,void 0),B([x({attribute:!1})],X.prototype,`onNavigate`,void 0),B([x({attribute:!1})],X.prototype,`onClose`,void 0),B([x({attribute:!1})],X.prototype,`onConfigSaved`,void 0),B([x({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),B([S()],X.prototype,`configResponse`,void 0),B([S()],X.prototype,`accessConfigResponse`,void 0),B([S()],X.prototype,`sessiondConfigResponse`,void 0),B([S()],X.prototype,`pluginsResponse`,void 0),B([S()],X.prototype,`selectedPluginConfigResponse`,void 0),B([S()],X.prototype,`selectedPluginsResponse`,void 0),B([S()],X.prototype,`packagesResponse`,void 0),B([S()],X.prototype,`loading`,void 0),B([S()],X.prototype,`accessLoading`,void 0),B([S()],X.prototype,`sessiondLoading`,void 0),B([S()],X.prototype,`pluginLoading`,void 0),B([S()],X.prototype,`packageLoading`,void 0),B([S()],X.prototype,`saving`,void 0),B([S()],X.prototype,`packageOperation`,void 0),B([S()],X.prototype,`error`,void 0),B([S()],X.prototype,`accessError`,void 0),B([S()],X.prototype,`sessiondError`,void 0),B([S()],X.prototype,`pluginError`,void 0),B([S()],X.prototype,`packageError`,void 0),B([S()],X.prototype,`savedMessage`,void 0),B([S()],X.prototype,`packageMessage`,void 0),X=B([b(`settings-dialog`)],X);function PD(e){return e instanceof Error?e.message:String(e)}var FD=class extends y{constructor(...e){super(...e),this.sessionsApi=co,this.loading=!0,this.error=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSystemPrompt()}updated(e){let t=e.has(`session`)&&LD(e.get(`session`))!==LD(this.session),n=e.has(`machine`)&&ID(e.get(`machine`))!==ID(this.machine);(t||n)&&this.isConnected&&this.loadSystemPrompt()}render(){return g`
5022
+ `}};B([x({attribute:!1})],X.prototype,`section`,void 0),B([x({attribute:!1})],X.prototype,`actions`,void 0),B([x({attribute:!1})],X.prototype,`machine`,void 0),B([x({attribute:!1})],X.prototype,`machineRuntime`,void 0),B([x({attribute:!1})],X.prototype,`onNavigate`,void 0),B([x({attribute:!1})],X.prototype,`onClose`,void 0),B([x({attribute:!1})],X.prototype,`onConfigSaved`,void 0),B([x({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),B([S()],X.prototype,`configResponse`,void 0),B([S()],X.prototype,`accessConfigResponse`,void 0),B([S()],X.prototype,`sessiondConfigResponse`,void 0),B([S()],X.prototype,`pluginsResponse`,void 0),B([S()],X.prototype,`selectedPluginConfigResponse`,void 0),B([S()],X.prototype,`selectedPluginsResponse`,void 0),B([S()],X.prototype,`packagesResponse`,void 0),B([S()],X.prototype,`loading`,void 0),B([S()],X.prototype,`accessLoading`,void 0),B([S()],X.prototype,`sessiondLoading`,void 0),B([S()],X.prototype,`pluginLoading`,void 0),B([S()],X.prototype,`packageLoading`,void 0),B([S()],X.prototype,`saving`,void 0),B([S()],X.prototype,`packageOperation`,void 0),B([S()],X.prototype,`error`,void 0),B([S()],X.prototype,`accessError`,void 0),B([S()],X.prototype,`sessiondError`,void 0),B([S()],X.prototype,`pluginError`,void 0),B([S()],X.prototype,`packageError`,void 0),B([S()],X.prototype,`savedMessage`,void 0),B([S()],X.prototype,`packageMessage`,void 0),X=B([b(`settings-dialog`)],X);function FD(e){return e instanceof Error?e.message:String(e)}var ID=class extends y{constructor(...e){super(...e),this.sessionsApi=co,this.loading=!0,this.error=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSystemPrompt()}updated(e){let t=e.has(`session`)&&RD(e.get(`session`))!==RD(this.session),n=e.has(`machine`)&&LD(e.get(`machine`))!==LD(this.machine);(t||n)&&this.isConnected&&this.loadSystemPrompt()}render(){return g`
4991
5023
  <div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
4992
5024
  <section class="dialog" role="dialog" aria-modal="true" aria-labelledby="system-prompt-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
4993
5025
  <header>
@@ -4996,7 +5028,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4996
5028
  <h1 id="system-prompt-dialog-title">System prompt</h1>
4997
5029
  </div>
4998
5030
  <button class="icon-button" type="button" title="Close system prompt" aria-label="Close system prompt" @click=${()=>{this.close()}}>
4999
- ${VD()}
5031
+ ${HD()}
5000
5032
  </button>
5001
5033
  </header>
5002
5034
  <div class="prompt-body" aria-live="polite">
@@ -5007,7 +5039,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5007
5039
  </footer>
5008
5040
  </section>
5009
5041
  </div>
5010
- `}renderPrompt(){return this.loading?g`<p class="prompt-state">Loading system prompt…</p>`:this.error===``?this.systemPrompt===void 0?g`<p class="prompt-state">Send a message to load the system prompt</p>`:this.systemPrompt===``?g`<p class="prompt-state">System prompt is empty (tools are disabled)</p>`:g`<pre class="system-prompt">${this.systemPrompt}</pre>`:g`<p class="prompt-state error">${this.error}</p>`}async loadSystemPrompt(){let e=this.session,t=e===void 0?void 0:zD(ID(this.machine),e),n=++this.loadRequestSequence;if(this.loading=!0,this.error=``,this.systemPrompt=void 0,e===void 0||t===void 0){this.loading=!1;return}try{let r=await this.sessionsApi.systemPrompt(e,ID(this.machine));if(!this.isCurrentLoad(n,t))return;this.systemPrompt=r.systemPrompt}catch(e){if(!this.isCurrentLoad(n,t))return;this.error=`Failed to load system prompt: ${BD(e)}`}finally{this.isCurrentLoad(n,t)&&(this.loading=!1)}}isCurrentLoad(e,t){let n=this.session;return e===this.loadRequestSequence&&n!==void 0&&zD(ID(this.machine),n)===t}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}static{this.styles=h`
5042
+ `}renderPrompt(){return this.loading?g`<p class="prompt-state">Loading system prompt…</p>`:this.error===``?this.systemPrompt===void 0?g`<p class="prompt-state">Send a message to load the system prompt</p>`:this.systemPrompt===``?g`<p class="prompt-state">System prompt is empty (tools are disabled)</p>`:g`<pre class="system-prompt">${this.systemPrompt}</pre>`:g`<p class="prompt-state error">${this.error}</p>`}async loadSystemPrompt(){let e=this.session,t=e===void 0?void 0:BD(LD(this.machine),e),n=++this.loadRequestSequence;if(this.loading=!0,this.error=``,this.systemPrompt=void 0,e===void 0||t===void 0){this.loading=!1;return}try{let r=await this.sessionsApi.systemPrompt(e,LD(this.machine));if(!this.isCurrentLoad(n,t))return;this.systemPrompt=r.systemPrompt}catch(e){if(!this.isCurrentLoad(n,t))return;this.error=`Failed to load system prompt: ${VD(e)}`}finally{this.isCurrentLoad(n,t)&&(this.loading=!1)}}isCurrentLoad(e,t){let n=this.session;return e===this.loadRequestSequence&&n!==void 0&&BD(LD(this.machine),n)===t}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}static{this.styles=h`
5011
5043
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
5012
5044
  * { box-sizing: border-box; }
5013
5045
  .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; }
@@ -5033,11 +5065,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5033
5065
  header, footer { padding: 12px; }
5034
5066
  .system-prompt, .prompt-state { padding: 12px; }
5035
5067
  }
5036
- `}};B([x({attribute:!1})],FD.prototype,`machine`,void 0),B([x({attribute:!1})],FD.prototype,`session`,void 0),B([x({attribute:!1})],FD.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],FD.prototype,`onClose`,void 0),B([S()],FD.prototype,`systemPrompt`,void 0),B([S()],FD.prototype,`loading`,void 0),B([S()],FD.prototype,`error`,void 0),FD=B([b(`system-prompt-dialog`)],FD);function ID(e){return e?.id??`local`}function LD(e){return e===void 0?void 0:RD(e)}function RD(e){return JSON.stringify([e.id,e.cwd])}function zD(e,t){return JSON.stringify([e,t.id,t.cwd])}function BD(e){return e instanceof Error?e.message:String(e)}function VD(){return _`
5068
+ `}};B([x({attribute:!1})],ID.prototype,`machine`,void 0),B([x({attribute:!1})],ID.prototype,`session`,void 0),B([x({attribute:!1})],ID.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],ID.prototype,`onClose`,void 0),B([S()],ID.prototype,`systemPrompt`,void 0),B([S()],ID.prototype,`loading`,void 0),B([S()],ID.prototype,`error`,void 0),ID=B([b(`system-prompt-dialog`)],ID);function LD(e){return e?.id??`local`}function RD(e){return e===void 0?void 0:zD(e)}function zD(e){return JSON.stringify([e.id,e.cwd])}function BD(e,t){return JSON.stringify([e,t.id,t.cwd])}function VD(e){return e instanceof Error?e.message:String(e)}function HD(){return _`
5037
5069
  <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
5038
5070
  <path d="M6 6l12 12M18 6 6 18"></path>
5039
5071
  </svg>
5040
- `}var HD=class extends y{constructor(...e){super(...e),this.tool=`core:workspace.files`,this.panels=[],this.hiddenTools=[],this.hideToolTabs=!1,this.onSelectTool=()=>void 0,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.`});let e=this.panelContext;if(e===void 0)return this.renderEmptyState({title:`Workspace tools unavailable`,body:`Try selecting the workspace again.`});let t=this.panels,n=t.filter(e=>!this.hiddenTools.includes(e.id)),r=t.find(e=>e.id===this.tool)??t[0];return g`
5072
+ `}var UD=class extends y{constructor(...e){super(...e),this.tool=`core:workspace.files`,this.panels=[],this.hiddenTools=[],this.hideToolTabs=!1,this.onSelectTool=()=>void 0,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.`});let e=this.panelContext;if(e===void 0)return this.renderEmptyState({title:`Workspace tools unavailable`,body:`Try selecting the workspace again.`});let t=this.panels,n=t.filter(e=>!this.hiddenTools.includes(e.id)),r=t.find(e=>e.id===this.tool)??t[0];return g`
5041
5073
  ${this.hideToolTabs?null:g`
5042
5074
  <header>
5043
5075
  <div class=${this.workspaceHeaderFrameClass()}>
@@ -5067,10 +5099,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5067
5099
  <h2>${e.title}</h2>
5068
5100
  ${e.body===void 0?null:g`<p>${e.body}</p>`}
5069
5101
  </section>
5070
- `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let 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(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=dm}};B([x({attribute:!1})],HD.prototype,`workspace`,void 0),B([x({attribute:!1})],HD.prototype,`panelContext`,void 0),B([x({attribute:!1})],HD.prototype,`emptyState`,void 0),B([x()],HD.prototype,`tool`,void 0),B([x({attribute:!1})],HD.prototype,`panels`,void 0),B([x({attribute:!1})],HD.prototype,`hiddenTools`,void 0),B([x({type:Boolean})],HD.prototype,`hideToolTabs`,void 0),B([x({attribute:!1})],HD.prototype,`onSelectTool`,void 0),B([C(`.workspace-header-strip`)],HD.prototype,`workspaceHeaderStrip`,void 0),B([S()],HD.prototype,`workspaceHeaderCanScrollLeft`,void 0),B([S()],HD.prototype,`workspaceHeaderCanScrollRight`,void 0),HD=B([b(`workspace-panel`)],HD);var UD=`important`,WD=` !important`,GD=H_(class extends U_{constructor(e){if(super(e),e.type!==V_.ATTRIBUTE||e.name!==`style`||e.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(e){return Object.keys(e).reduce((t,n)=>{let r=e[n];return r==null?t:t+`${n=n.includes(`-`)?n:n.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,`-$&`).toLowerCase()}:${r};`},``)}update(e,[t]){let{style:n}=e.element;if(this.ft===void 0)return this.ft=new Set(Object.keys(t)),this.render(t);for(let e of this.ft)t[e]??(this.ft.delete(e),e.includes(`-`)?n.removeProperty(e):n[e]=null);for(let e in t){let r=t[e];if(r!=null){this.ft.add(e);let t=typeof r==`string`&&r.endsWith(WD);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?UD:``):n[e]=r}}return Qe}}),KD=`#ffffff`,qD=`#000000`,JD=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],YD=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],XD={black:JD[0],red:JD[1],green:JD[2],yellow:JD[3],blue:JD[4],magenta:JD[5],cyan:JD[6],white:JD[7],brightBlack:JD[8],brightRed:JD[9],brightGreen:JD[10],brightYellow:JD[11],brightBlue:JD[12],brightMagenta:JD[13],brightCyan:JD[14],brightWhite:JD[15]};function ZD(e,t,n={}){let r=Math.max(0,Math.floor(t));if(e.length<=0||r===0)return{text:``,lines:[],physicalLineCount:0,viewportLine:0};let i=aO(n.theme),a=n.theme?.foreground??KD,o=n.theme?.background??qD,s=[],c=e.getNullCell(),l=-1;for(let t=0;t<e.length;t+=1){let u=e.getLine(t);if(u===void 0){s.push({text:``,runs:[],wrapped:!1});continue}let d=QD(u,r,c,{palette:i,foreground:a,background:o,drawBoldTextInBrightColors:n.drawBoldTextInBrightColors!==!1});s.push(d),(d.text!==``||d.runs.some(e=>e.style.background!==o))&&(l=t)}let u=Math.min(e.length-1,Math.max(0,e.baseY+e.cursorY)),d=Math.max(l,u),f=s.slice(0,d+1),p=[];for(let e of f){let t=p.at(-1);if(e.wrapped&&t!==void 0){t.text+=e.text,nO(t.runs,e.runs);continue}p.push({text:e.text,runs:e.runs.map(e=>({text:e.text,style:e.style}))})}return{text:p.map(e=>e.text).join(`
5071
- `),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function QD(e,t,n,r){let i=[],a=Math.min(t,e.length);for(let t=0;t<a;t+=1){let a=e.getCell(t,n);if(a===void 0){i.push({text:` `,meaningful:!1,style:tO(r)});continue}let o=a.getWidth();if(o===0)continue;let s=a.getChars();i.push({text:s===``?` `.repeat(Math.max(1,o)):s,meaningful:s!==``||!a.isAttributeDefault(),style:$D(a,r)})}let o=i.length-1;for(;o>=0&&i[o]?.meaningful!==!0;)--o;let s=[],c=``;for(let e=0;e<=o;e+=1){let t=i[e];t!==void 0&&(c+=t.text,rO(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function $D(e,t){let n=e.isInverse()!==0,r=eO(e,`foreground`,t),i=eO(e,`background`,t);if(n&&([r,i]=[i,r]),e.isBold()!==0&&t.drawBoldTextInBrightColors){let i=n?e.isBgPalette()?e.getBgColor():void 0:e.isFgPalette()?e.getFgColor():void 0;i!==void 0&&i>=0&&i<8&&(r=t.palette[i+8]??r)}return{foreground:r,background:i,bold:e.isBold()!==0,italic:e.isItalic()!==0,dim:e.isDim()!==0,underline:e.isUnderline()!==0,invisible:e.isInvisible()!==0,strikethrough:e.isStrikethrough()!==0,overline:e.isOverline()!==0}}function eO(e,t,n){let r=t===`foreground`?e.isFgRGB():e.isBgRGB(),i=t===`foreground`?e.isFgPalette():e.isBgPalette(),a=t===`foreground`?e.getFgColor():e.getBgColor();return r?oO(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function tO(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function nO(e,t){for(let n of t)rO(e,n)}function rO(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&iO(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function iO(e,t){return e.foreground===t.foreground&&e.background===t.background&&e.bold===t.bold&&e.italic===t.italic&&e.dim===t.dim&&e.underline===t.underline&&e.invisible===t.invisible&&e.strikethrough===t.strikethrough&&e.overline===t.overline}function aO(e){let t=[...JD];for(let n=0;n<YD.length;n+=1){let r=YD[n];if(r===void 0)continue;let i=e?.[r];typeof i==`string`&&(t[n]=i)}let n=[0,95,135,175,215,255];for(let e=0;e<216;e+=1){let r=n[Math.floor(e/36)%6]??0,i=n[Math.floor(e/6)%6]??0,a=n[e%6]??0;t.push(sO(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(sO(n,n,n))}for(let n=0;n<Math.min(e?.extendedAnsi?.length??0,240);n+=1){let r=e?.extendedAnsi?.[n];r!==void 0&&(t[n+16]=r)}return t}function oO(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function sO(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var cO=`pi-webui.terminal.softKeys`,lO=`(pointer: coarse), (max-width: 760px)`;function uO(e,t){return e??t}function dO(e){if(e===`true`)return!0;if(e===`false`)return!1}function fO(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(lO):void 0}function pO(e){return e?.matches===!0}function mO(e=fO()){return uO(gO(),pO(e))}function hO(){return gO()!==void 0}function gO(e=vO()){if(e!==void 0)try{return dO(e.getItem(cO))}catch{return}}function _O(e,t=vO()){if(t!==void 0)try{t.setItem(cO,String(e))}catch{}}function vO(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var yO=[{id:`escape`,label:`Esc`,ariaLabel:`Escape`,title:`Send Escape`},{id:`tab`,label:`Tab`,ariaLabel:`Tab`,title:`Send Tab`},{id:`ctrl-c`,label:`Ctrl+C`,ariaLabel:`Control C`,title:`Interrupt the foreground process`},{id:`ctrl-d`,label:`Ctrl+D`,ariaLabel:`Control D`,title:`Send EOF / close input`},{id:`ctrl-z`,label:`Ctrl+Z`,ariaLabel:`Control Z`,title:`Suspend the foreground process`},{id:`ctrl-l`,label:`Ctrl+L`,ariaLabel:`Control L`,title:`Clear / redraw the terminal`},{id:`ctrl-r`,label:`Ctrl+R`,ariaLabel:`Control R`,title:`Reverse search history`},{id:`ctrl-u`,label:`Ctrl+U`,ariaLabel:`Control U`,title:`Delete to the start of the line`},{id:`ctrl-w`,label:`Ctrl+W`,ariaLabel:`Control W`,title:`Delete the previous word`},{id:`arrow-left`,label:`←`,ariaLabel:`Left arrow`,title:`Move left`},{id:`arrow-up`,label:`↑`,ariaLabel:`Up arrow`,title:`Move up / previous command`},{id:`arrow-down`,label:`↓`,ariaLabel:`Down arrow`,title:`Move down / next command`},{id:`arrow-right`,label:`→`,ariaLabel:`Right arrow`,title:`Move right`},{id:`home`,label:`Home`,ariaLabel:`Home`,title:`Move to the start`},{id:`end`,label:`End`,ariaLabel:`End`,title:`Move to the end`},{id:`page-up`,label:`PgUp`,ariaLabel:`Page up`,title:`Page up`},{id:`page-down`,label:`PgDn`,ariaLabel:`Page down`,title:`Page down`},{id:`delete`,label:`Del`,ariaLabel:`Delete`,title:`Delete forward`},{id:`backspace`,label:`⌫`,ariaLabel:`Backspace`,title:`Backspace`},{id:`meta-backward-word`,label:`M-B`,ariaLabel:`Meta B`,title:`Move backward one word`},{id:`meta-forward-word`,label:`M-F`,ariaLabel:`Meta F`,title:`Move forward one word`}],bO=`\x1B`,xO=``;function SO(e,t){switch(e){case`escape`:return bO;case`tab`:return` `;case`ctrl-c`:return CO(`c`);case`ctrl-d`:return CO(`d`);case`ctrl-z`:return CO(`z`);case`ctrl-l`:return CO(`l`);case`ctrl-r`:return CO(`r`);case`ctrl-u`:return CO(`u`);case`ctrl-w`:return CO(`w`);case`arrow-left`:return wO(`D`,t);case`arrow-up`:return wO(`A`,t);case`arrow-down`:return wO(`B`,t);case`arrow-right`:return wO(`C`,t);case`home`:return TO(`H`,t);case`end`:return TO(`F`,t);case`page-up`:return`${bO}[5~`;case`page-down`:return`${bO}[6~`;case`delete`:return`${bO}[3~`;case`backspace`:return xO;case`meta-backward-word`:return`${bO}b`;case`meta-forward-word`:return`${bO}f`}}function CO(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function wO(e,t){return t?.applicationCursorKeysMode===!0?`${bO}O${e}`:`${bO}[${e}`}function TO(e,t){return t?.applicationCursorKeysMode===!0?`${bO}O${e}`:`${bO}[${e}`}var EO=8,DO=500,OO=class extends y{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(SO(e.id,this.modes),t)}onSoftKeyPointerDown(e,t){e.pointerType===`mouse`&&e.button!==0||(e.preventDefault(),this.pointerStart={pointerId:e.pointerId,key:t,clientX:e.clientX,clientY:e.clientY})}onSoftKeyPointerMove(e){let t=this.pointerStart;t?.pointerId===e.pointerId&&kO(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||kO(n,e))&&this.sendSoftKey(t,{refocus:e.pointerType===`mouse`}))}onSoftKeyPointerCancel(e){this.pointerStart?.pointerId===e.pointerId&&this.finishSoftKeyPointer()}finishSoftKeyPointer(){this.pointerStart=void 0,this.lastPointerFinishedAt=Date.now()}onSoftKeyClick(e,t){if(Date.now()-this.lastPointerFinishedAt<DO){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return g`
5102
+ `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let 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(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=dm}};B([x({attribute:!1})],UD.prototype,`workspace`,void 0),B([x({attribute:!1})],UD.prototype,`panelContext`,void 0),B([x({attribute:!1})],UD.prototype,`emptyState`,void 0),B([x()],UD.prototype,`tool`,void 0),B([x({attribute:!1})],UD.prototype,`panels`,void 0),B([x({attribute:!1})],UD.prototype,`hiddenTools`,void 0),B([x({type:Boolean})],UD.prototype,`hideToolTabs`,void 0),B([x({attribute:!1})],UD.prototype,`onSelectTool`,void 0),B([C(`.workspace-header-strip`)],UD.prototype,`workspaceHeaderStrip`,void 0),B([S()],UD.prototype,`workspaceHeaderCanScrollLeft`,void 0),B([S()],UD.prototype,`workspaceHeaderCanScrollRight`,void 0),UD=B([b(`workspace-panel`)],UD);var WD=`important`,GD=` !important`,KD=H_(class extends U_{constructor(e){if(super(e),e.type!==V_.ATTRIBUTE||e.name!==`style`||e.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(e){return Object.keys(e).reduce((t,n)=>{let r=e[n];return r==null?t:t+`${n=n.includes(`-`)?n:n.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,`-$&`).toLowerCase()}:${r};`},``)}update(e,[t]){let{style:n}=e.element;if(this.ft===void 0)return this.ft=new Set(Object.keys(t)),this.render(t);for(let e of this.ft)t[e]??(this.ft.delete(e),e.includes(`-`)?n.removeProperty(e):n[e]=null);for(let e in t){let r=t[e];if(r!=null){this.ft.add(e);let t=typeof r==`string`&&r.endsWith(GD);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?WD:``):n[e]=r}}return Qe}}),qD=`#ffffff`,JD=`#000000`,YD=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],XD=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],ZD={black:YD[0],red:YD[1],green:YD[2],yellow:YD[3],blue:YD[4],magenta:YD[5],cyan:YD[6],white:YD[7],brightBlack:YD[8],brightRed:YD[9],brightGreen:YD[10],brightYellow:YD[11],brightBlue:YD[12],brightMagenta:YD[13],brightCyan:YD[14],brightWhite:YD[15]};function QD(e,t,n={}){let r=Math.max(0,Math.floor(t));if(e.length<=0||r===0)return{text:``,lines:[],physicalLineCount:0,viewportLine:0};let i=oO(n.theme),a=n.theme?.foreground??qD,o=n.theme?.background??JD,s=[],c=e.getNullCell(),l=-1;for(let t=0;t<e.length;t+=1){let u=e.getLine(t);if(u===void 0){s.push({text:``,runs:[],wrapped:!1});continue}let d=$D(u,r,c,{palette:i,foreground:a,background:o,drawBoldTextInBrightColors:n.drawBoldTextInBrightColors!==!1});s.push(d),(d.text!==``||d.runs.some(e=>e.style.background!==o))&&(l=t)}let u=Math.min(e.length-1,Math.max(0,e.baseY+e.cursorY)),d=Math.max(l,u),f=s.slice(0,d+1),p=[];for(let e of f){let t=p.at(-1);if(e.wrapped&&t!==void 0){t.text+=e.text,rO(t.runs,e.runs);continue}p.push({text:e.text,runs:e.runs.map(e=>({text:e.text,style:e.style}))})}return{text:p.map(e=>e.text).join(`
5103
+ `),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function $D(e,t,n,r){let i=[],a=Math.min(t,e.length);for(let t=0;t<a;t+=1){let a=e.getCell(t,n);if(a===void 0){i.push({text:` `,meaningful:!1,style:nO(r)});continue}let o=a.getWidth();if(o===0)continue;let s=a.getChars();i.push({text:s===``?` `.repeat(Math.max(1,o)):s,meaningful:s!==``||!a.isAttributeDefault(),style:eO(a,r)})}let o=i.length-1;for(;o>=0&&i[o]?.meaningful!==!0;)--o;let s=[],c=``;for(let e=0;e<=o;e+=1){let t=i[e];t!==void 0&&(c+=t.text,iO(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function eO(e,t){let n=e.isInverse()!==0,r=tO(e,`foreground`,t),i=tO(e,`background`,t);if(n&&([r,i]=[i,r]),e.isBold()!==0&&t.drawBoldTextInBrightColors){let i=n?e.isBgPalette()?e.getBgColor():void 0:e.isFgPalette()?e.getFgColor():void 0;i!==void 0&&i>=0&&i<8&&(r=t.palette[i+8]??r)}return{foreground:r,background:i,bold:e.isBold()!==0,italic:e.isItalic()!==0,dim:e.isDim()!==0,underline:e.isUnderline()!==0,invisible:e.isInvisible()!==0,strikethrough:e.isStrikethrough()!==0,overline:e.isOverline()!==0}}function tO(e,t,n){let r=t===`foreground`?e.isFgRGB():e.isBgRGB(),i=t===`foreground`?e.isFgPalette():e.isBgPalette(),a=t===`foreground`?e.getFgColor():e.getBgColor();return r?sO(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function nO(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function rO(e,t){for(let n of t)iO(e,n)}function iO(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&aO(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function aO(e,t){return e.foreground===t.foreground&&e.background===t.background&&e.bold===t.bold&&e.italic===t.italic&&e.dim===t.dim&&e.underline===t.underline&&e.invisible===t.invisible&&e.strikethrough===t.strikethrough&&e.overline===t.overline}function oO(e){let t=[...YD];for(let n=0;n<XD.length;n+=1){let r=XD[n];if(r===void 0)continue;let i=e?.[r];typeof i==`string`&&(t[n]=i)}let n=[0,95,135,175,215,255];for(let e=0;e<216;e+=1){let r=n[Math.floor(e/36)%6]??0,i=n[Math.floor(e/6)%6]??0,a=n[e%6]??0;t.push(cO(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(cO(n,n,n))}for(let n=0;n<Math.min(e?.extendedAnsi?.length??0,240);n+=1){let r=e?.extendedAnsi?.[n];r!==void 0&&(t[n+16]=r)}return t}function sO(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function cO(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var lO=`pi-webui.terminal.softKeys`,uO=`(pointer: coarse), (max-width: 760px)`;function dO(e,t){return e??t}function fO(e){if(e===`true`)return!0;if(e===`false`)return!1}function pO(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(uO):void 0}function mO(e){return e?.matches===!0}function hO(e=pO()){return dO(_O(),mO(e))}function gO(){return _O()!==void 0}function _O(e=yO()){if(e!==void 0)try{return fO(e.getItem(lO))}catch{return}}function vO(e,t=yO()){if(t!==void 0)try{t.setItem(lO,String(e))}catch{}}function yO(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var bO=[{id:`escape`,label:`Esc`,ariaLabel:`Escape`,title:`Send Escape`},{id:`tab`,label:`Tab`,ariaLabel:`Tab`,title:`Send Tab`},{id:`ctrl-c`,label:`Ctrl+C`,ariaLabel:`Control C`,title:`Interrupt the foreground process`},{id:`ctrl-d`,label:`Ctrl+D`,ariaLabel:`Control D`,title:`Send EOF / close input`},{id:`ctrl-z`,label:`Ctrl+Z`,ariaLabel:`Control Z`,title:`Suspend the foreground process`},{id:`ctrl-l`,label:`Ctrl+L`,ariaLabel:`Control L`,title:`Clear / redraw the terminal`},{id:`ctrl-r`,label:`Ctrl+R`,ariaLabel:`Control R`,title:`Reverse search history`},{id:`ctrl-u`,label:`Ctrl+U`,ariaLabel:`Control U`,title:`Delete to the start of the line`},{id:`ctrl-w`,label:`Ctrl+W`,ariaLabel:`Control W`,title:`Delete the previous word`},{id:`arrow-left`,label:`←`,ariaLabel:`Left arrow`,title:`Move left`},{id:`arrow-up`,label:`↑`,ariaLabel:`Up arrow`,title:`Move up / previous command`},{id:`arrow-down`,label:`↓`,ariaLabel:`Down arrow`,title:`Move down / next command`},{id:`arrow-right`,label:`→`,ariaLabel:`Right arrow`,title:`Move right`},{id:`home`,label:`Home`,ariaLabel:`Home`,title:`Move to the start`},{id:`end`,label:`End`,ariaLabel:`End`,title:`Move to the end`},{id:`page-up`,label:`PgUp`,ariaLabel:`Page up`,title:`Page up`},{id:`page-down`,label:`PgDn`,ariaLabel:`Page down`,title:`Page down`},{id:`delete`,label:`Del`,ariaLabel:`Delete`,title:`Delete forward`},{id:`backspace`,label:`⌫`,ariaLabel:`Backspace`,title:`Backspace`},{id:`meta-backward-word`,label:`M-B`,ariaLabel:`Meta B`,title:`Move backward one word`},{id:`meta-forward-word`,label:`M-F`,ariaLabel:`Meta F`,title:`Move forward one word`}],xO=`\x1B`,SO=``;function CO(e,t){switch(e){case`escape`:return xO;case`tab`:return` `;case`ctrl-c`:return wO(`c`);case`ctrl-d`:return wO(`d`);case`ctrl-z`:return wO(`z`);case`ctrl-l`:return wO(`l`);case`ctrl-r`:return wO(`r`);case`ctrl-u`:return wO(`u`);case`ctrl-w`:return wO(`w`);case`arrow-left`:return TO(`D`,t);case`arrow-up`:return TO(`A`,t);case`arrow-down`:return TO(`B`,t);case`arrow-right`:return TO(`C`,t);case`home`:return EO(`H`,t);case`end`:return EO(`F`,t);case`page-up`:return`${xO}[5~`;case`page-down`:return`${xO}[6~`;case`delete`:return`${xO}[3~`;case`backspace`:return SO;case`meta-backward-word`:return`${xO}b`;case`meta-forward-word`:return`${xO}f`}}function wO(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function TO(e,t){return t?.applicationCursorKeysMode===!0?`${xO}O${e}`:`${xO}[${e}`}function EO(e,t){return t?.applicationCursorKeysMode===!0?`${xO}O${e}`:`${xO}[${e}`}var DO=8,OO=500,kO=class extends y{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(CO(e.id,this.modes),t)}onSoftKeyPointerDown(e,t){e.pointerType===`mouse`&&e.button!==0||(e.preventDefault(),this.pointerStart={pointerId:e.pointerId,key:t,clientX:e.clientX,clientY:e.clientY})}onSoftKeyPointerMove(e){let t=this.pointerStart;t?.pointerId===e.pointerId&&AO(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||AO(n,e))&&this.sendSoftKey(t,{refocus:e.pointerType===`mouse`}))}onSoftKeyPointerCancel(e){this.pointerStart?.pointerId===e.pointerId&&this.finishSoftKeyPointer()}finishSoftKeyPointer(){this.pointerStart=void 0,this.lastPointerFinishedAt=Date.now()}onSoftKeyClick(e,t){if(Date.now()-this.lastPointerFinishedAt<OO){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return g`
5072
5104
  <div class="terminal-soft-keys" role="toolbar" aria-label="Terminal soft keys">
5073
- ${yO.map(e=>g`
5105
+ ${bO.map(e=>g`
5074
5106
  <button
5075
5107
  type="button"
5076
5108
  class="soft-key"
@@ -5090,7 +5122,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5090
5122
  .terminal-soft-keys::-webkit-scrollbar { display: none; }
5091
5123
  button { display: inline-flex; align-items: center; gap: 6px; flex: 0 0 auto; max-width: none; min-height: 34px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 6px 9px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; cursor: pointer; touch-action: pan-x; -webkit-touch-callout: none; user-select: none; }
5092
5124
  button:disabled { opacity: .5; cursor: not-allowed; }
5093
- `}};B([x({attribute:!1})],OO.prototype,`modes`,void 0),B([x({type:Boolean})],OO.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],OO.prototype,`onInput`,void 0),OO=B([b(`terminal-soft-keys`)],OO);function kO(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>EO}var AO=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>HO,terminalBackgroundWithOpacity:()=>JO}),jO={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},MO={cols:100,rows:30},NO=1e3,PO=`--pi-terminal-effective-bg`,FO=`--pi-terminal-ui-opacity`,Z=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.autoStart=!1,this.fontSize=13,this.bgOpacity=100,this.onSelectTerminal=()=>void 0,this.terminals=[],this.commandRuns=[],this.loading=!1,this.visible=!1,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.defaultSoftKeysEnvironment=!1,this.softKeysEnabled=mO(),this.suppressTerminalInput=!1,this.softKeysDefaultEnvironmentMedia=fO(),this.softKeysPreferenceStored=hO(),this.onSoftKeysDefaultEnvironmentChange=()=>{this.syncDefaultSoftKeysEnvironment()}}connectedCallback(){super.connectedCallback(),this.syncTerminalBackground(),this.syncDefaultSoftKeysEnvironment(),this.softKeysDefaultEnvironmentMedia?.addEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.themeObserver=new MutationObserver(()=>{this.applyTerminalTheme()}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`,`style`,`data-theme`]})}firstUpdated(){this.intersectionObserver=new IntersectionObserver(e=>{this.visible=e[0]?.isIntersecting===!0}),this.intersectionObserver.observe(this)}disconnectedCallback(){this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.themeObserver?.disconnect(),this.themeObserver=void 0,this.softKeysDefaultEnvironmentMedia?.removeEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.updateCommandRunPolling(!1),this.disposeTerminalView(),super.disconnectedCallback()}syncDefaultSoftKeysEnvironment(){let e=pO(this.softKeysDefaultEnvironmentMedia),t=this.softKeysEnabled;this.defaultSoftKeysEnvironment=e,this.softKeysPreferenceStored||(this.softKeysEnabled=e),this.softKeysEnabled!==t&&this.scheduleFitAndNotify()}scheduleFitAndNotify(){this.updateComplete.then(()=>{this.fitAndNotify()})}willUpdate(e){e.has(`bgOpacity`)&&this.syncTerminalBackground();let t=this.workspace===void 0?void 0:JSON.stringify([this.machineId,this.workspace.path]);if(t!==this.observedWorkspaceScope){this.observedWorkspaceScope=t,this.loadedCwd=void 0,this.autoStartConsumedCwd=void 0,this.terminals=[],this.commandRuns=[],this.selectedId=void 0,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.updateCommandRunPolling(!1),this.disposeTerminalView();return}if(e.has(`selectedTerminalId`)){if(e.get(`selectedTerminalId`)!==void 0&&this.selectedTerminalId===void 0){this.loadedCwd=void 0,this.selectTerminalIdInView(void 0);return}this.applyRequestedTerminalSelection()}}updated(e){this.visible?this.hasPendingCommandRuns()&&this.updateCommandRunPolling(!0):this.updateCommandRunPolling(!1),this.loadVisibleWorkspaceTerminals(),e.has(`selectedTerminalId`)&&this.shouldReloadForRequestedTerminal()&&this.loadTerminals(),e.has(`fontSize`)&&this.terminal!==void 0&&(this.terminal.options.fontSize=this.fontSize,this.fitAndNotify()),e.has(`bgOpacity`)&&this.applyTerminalTheme(),this.ensureTerminalView()}loadVisibleWorkspaceTerminals(){let e=this.workspace?.path;!this.visible||e===void 0||e===this.loadedCwd||(this.loadedCwd=e,this.loadTerminals())}async loadTerminals(){this.loading=!0,this.error=void 0;try{let e=this.workspace;if(e===void 0)return;let t=this.consumeAutoStart(),[n,r]=await Promise.all([lo.terminals(e.projectId,e.id,this.machineId),lo.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId)]);this.terminals=n,this.commandRuns=r,this.selectPreferredLoadedTerminal({replaceUrl:!0}),this.updateCommandRunPolling(this.hasPendingCommandRuns(r)),n.length===0&&t&&await this.startTerminal()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}}applyRequestedTerminalSelection(){this.selectedTerminalId!==void 0&&!this.terminals.some(e=>e.id===this.selectedTerminalId)||this.selectPreferredLoadedTerminal({replaceUrl:!0})}consumeAutoStart(){let e=this.workspace?.path;return!this.autoStart||e===void 0||this.autoStartConsumedCwd===e?!1:(this.autoStartConsumedCwd=e,!0)}shouldReloadForRequestedTerminal(){let e=this.workspace?.path;return this.visible&&e!==void 0&&e===this.loadedCwd&&this.selectedTerminalId!==void 0&&!this.loading&&!this.terminals.some(e=>e.id===this.selectedTerminalId)}selectPreferredLoadedTerminal(e){let t=bf(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=xf(this.terminals)),this.selectTerminalIdInView(t?.id),(t?.id!==this.selectedTerminalId||t===void 0&&this.selectedTerminalId!==void 0)&&this.onSelectTerminal(t?.id,{replace:e?.replaceUrl===!0})}selectTerminalIdInView(e){this.selectedId!==e&&(this.selectedId=e,this.disposeTerminalView())}async startTerminal(){if(this.workspace!==void 0){this.error=void 0;try{let e=this.measureTerminalSize()??MO,t=await lo.startTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=[...this.terminals,t],this.selectTerminal(t.id)}catch(e){this.error=e instanceof Error?e.message:String(e)}}}async closeTerminal(e,t){t.stopPropagation();try{if(this.workspace===void 0)return;await lo.closeTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);let t=this.terminals.filter(t=>t.id!==e);if(this.terminals=t,this.selectedId===e||this.selectedTerminalId===e){let e=xf(t)?.id;this.selectTerminalIdInView(e),this.onSelectTerminal(e,{replace:!0})}}catch(e){this.error=e instanceof Error?e.message:String(e)}}selectTerminal(e){this.selectedId!==e&&this.selectTerminalIdInView(e),this.onSelectTerminal(e)}selectedTerminalInfo(){return this.terminals.find(e=>e.id===this.selectedId)}selectedCommandRun(){let e=this.selectedTerminalInfo()?.commandRunId;if(e!==void 0)return this.commandRuns.find(t=>t.id===e)}async loadCommandRuns(){let e=this.workspace;if(e!==void 0)try{let t=await lo.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&zO(t))),this.updateCommandRunPolling(this.hasPendingCommandRuns(t))}catch(e){this.error=e instanceof Error?e.message:String(e)}}updateCommandRunPolling(e){if(e&&this.commandRunPollTimer===void 0){this.commandRunPollTimer=window.setInterval(()=>{this.loadCommandRuns()},NO);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(zO)}async cancelCommandRun(e){if(!(!zO(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await lo.cancelCommandRun(e.id,this.machineId),await this.loadCommandRuns()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.cancellingRunIds=this.cancellingRunIds.filter(t=>t!==e.id)}}}async continueTerminal(e){if(!(this.workspace===void 0||this.continuingTerminalIds.includes(e))){this.error=void 0,this.continuingTerminalIds=[...this.continuingTerminalIds,e];try{let t=await lo.continueTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=this.terminals.map(n=>n.id===e?t:n),this.socket===void 0&&this.disposeTerminalView(),this.fitAndNotify(),this.terminal?.focus()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.continuingTerminalIds=this.continuingTerminalIds.filter(t=>t!==e)}}}ensureTerminalView(){let e=this.workspace,t=this.terminalHostElement();if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||t===void 0||e===void 0)return;let n=new re(WO(this)),r=new ie;n.loadAddon(r),n.open(t),this.terminal=n,this.fitAddon=r,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(t),n.onData(e=>{this.suppressTerminalInput||this.copySnapshot!==void 0||this.sendTerminalInput(e)});let i=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,n,i),requestAnimationFrame(()=>{this.fitAndNotify()}),n.focus()}connectSocket(e,t,n,r,i){let a=vo(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.fitAndNotify()}),a.addEventListener(`message`,e=>{this.handleSocketMessage(e.data,n,r)}),a.addEventListener(`close`,()=>{this.socket===a&&(this.socket=void 0)})}async handleSocketMessage(e,t,n){try{let r=VO(await UO(e));r.type===`output`&&this.writeTerminalOutput(n,r.data,r.replay===!0),r.type===`exit`&&(n.writeln(`\r\n[process exited${r.exitCode===void 0?``:` with code ${String(r.exitCode)}`}]`),this.terminals=this.terminals.map(e=>e.id===t?{...e,exited:!0,...r.exitCode===void 0?{}:{exitCode:r.exitCode}}:e),this.loadCommandRuns()),r.type===`error`&&n.writeln(`\r\n[terminal error: ${r.message}]`)}catch(e){n.writeln(`\r\n[terminal error: ${e instanceof Error?e.message:String(e)}]`)}}writeTerminalOutput(e,t,n){if(!n){e.write(t);return}this.suppressTerminalInput=!0,e.write(t,()=>{this.suppressTerminalInput=!1})}fitAndNotify(){let e=this.fitTerminal();e!==void 0&&this.send({type:`resize`,...e})}fitTerminal(){if(this.fitAddon===void 0||this.terminal===void 0)return;let e=YO(this.fitAddon.proposeDimensions());if(e!==void 0)return this.fitAddon.fit(),e}measureTerminalSize(){let e=this.fitTerminal();if(e!==void 0)return e;let t=this.terminalHostElement();if(this.terminal!==void 0||t===void 0)return;let n=new re(WO(this)),r=new ie;n.loadAddon(r),n.open(t);let i=YO(r.proposeDimensions());return n.dispose(),i}terminalHostElement(){let e=this.terminalHost;return e instanceof HTMLDivElement?e:void 0}applyTerminalTheme(){this.syncTerminalBackground(),this.terminal!==void 0&&(this.terminal.options.theme=GO(this))}syncTerminalBackground(){let e=qO(this.bgOpacity),t=JO(KO(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(PO,t),this.style.setProperty(FO,`${String(e)}%`)}sendTerminalInput(e){let t=HO(e);t!==``&&this.send({type:`input`,data:t})}sendSoftKeyInput(e,t){this.copySnapshot===void 0&&(this.sendTerminalInput(e),t.refocus&&this.focusTerminal())}focusTerminal(){let e=this.terminal;e!==void 0&&(e.focus(),requestAnimationFrame(()=>{e.focus()}))}send(e){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.socket?.close(),this.socket=void 0,this.terminal?.dispose(),this.terminal=void 0,this.fitAddon=void 0,this.copySnapshot=void 0,this.copyStatus=void 0}renderCommandRunNotice(){let e=this.selectedCommandRun();if(e===void 0)return null;let t=this.selectedTerminalInfo();if(zO(e)){let t=this.cancellingRunIds.includes(e.id);return g`
5125
+ `}};B([x({attribute:!1})],kO.prototype,`modes`,void 0),B([x({type:Boolean})],kO.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],kO.prototype,`onInput`,void 0),kO=B([b(`terminal-soft-keys`)],kO);function AO(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>DO}var jO=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>UO,terminalBackgroundWithOpacity:()=>YO}),MO={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},NO={cols:100,rows:30},PO=1e3,FO=`--pi-terminal-effective-bg`,IO=`--pi-terminal-ui-opacity`,Z=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.autoStart=!1,this.fontSize=13,this.bgOpacity=100,this.onSelectTerminal=()=>void 0,this.terminals=[],this.commandRuns=[],this.loading=!1,this.visible=!1,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.defaultSoftKeysEnvironment=!1,this.softKeysEnabled=hO(),this.suppressTerminalInput=!1,this.softKeysDefaultEnvironmentMedia=pO(),this.softKeysPreferenceStored=gO(),this.onSoftKeysDefaultEnvironmentChange=()=>{this.syncDefaultSoftKeysEnvironment()}}connectedCallback(){super.connectedCallback(),this.syncTerminalBackground(),this.syncDefaultSoftKeysEnvironment(),this.softKeysDefaultEnvironmentMedia?.addEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.themeObserver=new MutationObserver(()=>{this.applyTerminalTheme()}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`,`style`,`data-theme`]})}firstUpdated(){this.intersectionObserver=new IntersectionObserver(e=>{this.visible=e[0]?.isIntersecting===!0}),this.intersectionObserver.observe(this)}disconnectedCallback(){this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.themeObserver?.disconnect(),this.themeObserver=void 0,this.softKeysDefaultEnvironmentMedia?.removeEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.updateCommandRunPolling(!1),this.disposeTerminalView(),super.disconnectedCallback()}syncDefaultSoftKeysEnvironment(){let e=mO(this.softKeysDefaultEnvironmentMedia),t=this.softKeysEnabled;this.defaultSoftKeysEnvironment=e,this.softKeysPreferenceStored||(this.softKeysEnabled=e),this.softKeysEnabled!==t&&this.scheduleFitAndNotify()}scheduleFitAndNotify(){this.updateComplete.then(()=>{this.fitAndNotify()})}willUpdate(e){e.has(`bgOpacity`)&&this.syncTerminalBackground();let t=this.workspace===void 0?void 0:JSON.stringify([this.machineId,this.workspace.path]);if(t!==this.observedWorkspaceScope){this.observedWorkspaceScope=t,this.loadedCwd=void 0,this.autoStartConsumedCwd=void 0,this.terminals=[],this.commandRuns=[],this.selectedId=void 0,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.updateCommandRunPolling(!1),this.disposeTerminalView();return}if(e.has(`selectedTerminalId`)){if(e.get(`selectedTerminalId`)!==void 0&&this.selectedTerminalId===void 0){this.loadedCwd=void 0,this.selectTerminalIdInView(void 0);return}this.applyRequestedTerminalSelection()}}updated(e){this.visible?this.hasPendingCommandRuns()&&this.updateCommandRunPolling(!0):this.updateCommandRunPolling(!1),this.loadVisibleWorkspaceTerminals(),e.has(`selectedTerminalId`)&&this.shouldReloadForRequestedTerminal()&&this.loadTerminals(),e.has(`fontSize`)&&this.terminal!==void 0&&(this.terminal.options.fontSize=this.fontSize,this.fitAndNotify()),e.has(`bgOpacity`)&&this.applyTerminalTheme(),this.ensureTerminalView()}loadVisibleWorkspaceTerminals(){let e=this.workspace?.path;!this.visible||e===void 0||e===this.loadedCwd||(this.loadedCwd=e,this.loadTerminals())}async loadTerminals(){this.loading=!0,this.error=void 0;try{let e=this.workspace;if(e===void 0)return;let t=this.consumeAutoStart(),[n,r]=await Promise.all([lo.terminals(e.projectId,e.id,this.machineId),lo.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId)]);this.terminals=n,this.commandRuns=r,this.selectPreferredLoadedTerminal({replaceUrl:!0}),this.updateCommandRunPolling(this.hasPendingCommandRuns(r)),n.length===0&&t&&await this.startTerminal()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}}applyRequestedTerminalSelection(){this.selectedTerminalId!==void 0&&!this.terminals.some(e=>e.id===this.selectedTerminalId)||this.selectPreferredLoadedTerminal({replaceUrl:!0})}consumeAutoStart(){let e=this.workspace?.path;return!this.autoStart||e===void 0||this.autoStartConsumedCwd===e?!1:(this.autoStartConsumedCwd=e,!0)}shouldReloadForRequestedTerminal(){let e=this.workspace?.path;return this.visible&&e!==void 0&&e===this.loadedCwd&&this.selectedTerminalId!==void 0&&!this.loading&&!this.terminals.some(e=>e.id===this.selectedTerminalId)}selectPreferredLoadedTerminal(e){let t=bf(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=xf(this.terminals)),this.selectTerminalIdInView(t?.id),(t?.id!==this.selectedTerminalId||t===void 0&&this.selectedTerminalId!==void 0)&&this.onSelectTerminal(t?.id,{replace:e?.replaceUrl===!0})}selectTerminalIdInView(e){this.selectedId!==e&&(this.selectedId=e,this.disposeTerminalView())}async startTerminal(){if(this.workspace!==void 0){this.error=void 0;try{let e=this.measureTerminalSize()??NO,t=await lo.startTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=[...this.terminals,t],this.selectTerminal(t.id)}catch(e){this.error=e instanceof Error?e.message:String(e)}}}async closeTerminal(e,t){t.stopPropagation();try{if(this.workspace===void 0)return;await lo.closeTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);let t=this.terminals.filter(t=>t.id!==e);if(this.terminals=t,this.selectedId===e||this.selectedTerminalId===e){let e=xf(t)?.id;this.selectTerminalIdInView(e),this.onSelectTerminal(e,{replace:!0})}}catch(e){this.error=e instanceof Error?e.message:String(e)}}selectTerminal(e){this.selectedId!==e&&this.selectTerminalIdInView(e),this.onSelectTerminal(e)}selectedTerminalInfo(){return this.terminals.find(e=>e.id===this.selectedId)}selectedCommandRun(){let e=this.selectedTerminalInfo()?.commandRunId;if(e!==void 0)return this.commandRuns.find(t=>t.id===e)}async loadCommandRuns(){let e=this.workspace;if(e!==void 0)try{let t=await lo.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&BO(t))),this.updateCommandRunPolling(this.hasPendingCommandRuns(t))}catch(e){this.error=e instanceof Error?e.message:String(e)}}updateCommandRunPolling(e){if(e&&this.commandRunPollTimer===void 0){this.commandRunPollTimer=window.setInterval(()=>{this.loadCommandRuns()},PO);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(BO)}async cancelCommandRun(e){if(!(!BO(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await lo.cancelCommandRun(e.id,this.machineId),await this.loadCommandRuns()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.cancellingRunIds=this.cancellingRunIds.filter(t=>t!==e.id)}}}async continueTerminal(e){if(!(this.workspace===void 0||this.continuingTerminalIds.includes(e))){this.error=void 0,this.continuingTerminalIds=[...this.continuingTerminalIds,e];try{let t=await lo.continueTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=this.terminals.map(n=>n.id===e?t:n),this.socket===void 0&&this.disposeTerminalView(),this.fitAndNotify(),this.terminal?.focus()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.continuingTerminalIds=this.continuingTerminalIds.filter(t=>t!==e)}}}ensureTerminalView(){let e=this.workspace,t=this.terminalHostElement();if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||t===void 0||e===void 0)return;let n=new re(GO(this)),r=new ie;n.loadAddon(r),n.open(t),this.terminal=n,this.fitAddon=r,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(t),n.onData(e=>{this.suppressTerminalInput||this.copySnapshot!==void 0||this.sendTerminalInput(e)});let i=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,n,i),requestAnimationFrame(()=>{this.fitAndNotify()}),n.focus()}connectSocket(e,t,n,r,i){let a=vo(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.fitAndNotify()}),a.addEventListener(`message`,e=>{this.handleSocketMessage(e.data,n,r)}),a.addEventListener(`close`,()=>{this.socket===a&&(this.socket=void 0)})}async handleSocketMessage(e,t,n){try{let r=HO(await WO(e));r.type===`output`&&this.writeTerminalOutput(n,r.data,r.replay===!0),r.type===`exit`&&(n.writeln(`\r\n[process exited${r.exitCode===void 0?``:` with code ${String(r.exitCode)}`}]`),this.terminals=this.terminals.map(e=>e.id===t?{...e,exited:!0,...r.exitCode===void 0?{}:{exitCode:r.exitCode}}:e),this.loadCommandRuns()),r.type===`error`&&n.writeln(`\r\n[terminal error: ${r.message}]`)}catch(e){n.writeln(`\r\n[terminal error: ${e instanceof Error?e.message:String(e)}]`)}}writeTerminalOutput(e,t,n){if(!n){e.write(t);return}this.suppressTerminalInput=!0,e.write(t,()=>{this.suppressTerminalInput=!1})}fitAndNotify(){let e=this.fitTerminal();e!==void 0&&this.send({type:`resize`,...e})}fitTerminal(){if(this.fitAddon===void 0||this.terminal===void 0)return;let e=XO(this.fitAddon.proposeDimensions());if(e!==void 0)return this.fitAddon.fit(),e}measureTerminalSize(){let e=this.fitTerminal();if(e!==void 0)return e;let t=this.terminalHostElement();if(this.terminal!==void 0||t===void 0)return;let n=new re(GO(this)),r=new ie;n.loadAddon(r),n.open(t);let i=XO(r.proposeDimensions());return n.dispose(),i}terminalHostElement(){let e=this.terminalHost;return e instanceof HTMLDivElement?e:void 0}applyTerminalTheme(){this.syncTerminalBackground(),this.terminal!==void 0&&(this.terminal.options.theme=KO(this))}syncTerminalBackground(){let e=JO(this.bgOpacity),t=YO(qO(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(FO,t),this.style.setProperty(IO,`${String(e)}%`)}sendTerminalInput(e){let t=UO(e);t!==``&&this.send({type:`input`,data:t})}sendSoftKeyInput(e,t){this.copySnapshot===void 0&&(this.sendTerminalInput(e),t.refocus&&this.focusTerminal())}focusTerminal(){let e=this.terminal;e!==void 0&&(e.focus(),requestAnimationFrame(()=>{e.focus()}))}send(e){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.socket?.close(),this.socket=void 0,this.terminal?.dispose(),this.terminal=void 0,this.fitAddon=void 0,this.copySnapshot=void 0,this.copyStatus=void 0}renderCommandRunNotice(){let e=this.selectedCommandRun();if(e===void 0)return null;let t=this.selectedTerminalInfo();if(BO(e)){let t=this.cancellingRunIds.includes(e.id);return g`
5094
5126
  <section class="command-run-notice running">
5095
5127
  <div>
5096
5128
  <strong>${e.title}</strong>
@@ -5102,13 +5134,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5102
5134
  `}if(t?.exited===!0){let n=this.continuingTerminalIds.includes(t.id);return g`
5103
5135
  <section class=${`command-run-notice ${e.status}`}>
5104
5136
  <div>
5105
- <strong>${BO(e)}</strong>
5137
+ <strong>${VO(e)}</strong>
5106
5138
  <p>Output is preserved. Continue in a shell to inspect or run follow-up commands.</p>
5107
5139
  <code>${e.command}</code>
5108
5140
  </div>
5109
5141
  <button ?disabled=${n} @click=${()=>{this.continueTerminal(t.id)}}>${n?`Starting shell…`:`Continue in shell`}</button>
5110
5142
  </section>
5111
- `}return null}enterCopyMode(){this.copySnapshot===void 0&&this.captureCopySnapshot()}refreshCopyMode(){this.copySnapshot!==void 0&&this.captureCopySnapshot()}captureCopySnapshot(){let e=this.terminal;if(e===void 0)return;let t=ZD(e.buffer.active,e.cols,{theme:e.options.theme,drawBoldTextInBrightColors:e.options.drawBoldTextInBrightColors});this.copySnapshot=t,this.copyStatus=void 0,e.blur(),this.updateComplete.then(()=>{let n=this.terminalCopySelector;if(n==null)return;let r=Math.max(0,t.physicalLineCount-e.rows),i=Math.min(r,t.viewportLine);n.scrollTop=(r===0?0:i/r)*Math.max(0,n.scrollHeight-n.clientHeight),this.syncCopySnapshotScroll()})}exitCopyMode(){this.copySnapshot!==void 0&&(this.copySnapshot=void 0,this.copyStatus=void 0)}syncCopySnapshotScroll(){let e=this.terminalCopySelector,t=this.terminalCopyContent;if(e==null||t==null)return;let n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.max(0,t.scrollHeight-t.clientHeight),i=Math.max(0,e.scrollWidth-e.clientWidth),a=Math.max(0,t.scrollWidth-t.clientWidth);t.scrollTop=IO(e.scrollTop,n,r),t.scrollLeft=IO(e.scrollLeft,i,a)}async copyAllSnapshotText(){let e=this.copySnapshot?.text??``;if(e===``){this.copyStatus=`No terminal output to copy.`;return}this.copyStatus=await Dy(e)?`Copied all terminal output.`:`Unable to copy terminal output.`}renderCopyModeToggle(){if(this.selectedId===void 0)return null;let e=this.copySnapshot!==void 0;return g`
5143
+ `}return null}enterCopyMode(){this.copySnapshot===void 0&&this.captureCopySnapshot()}refreshCopyMode(){this.copySnapshot!==void 0&&this.captureCopySnapshot()}captureCopySnapshot(){let e=this.terminal;if(e===void 0)return;let t=QD(e.buffer.active,e.cols,{theme:e.options.theme,drawBoldTextInBrightColors:e.options.drawBoldTextInBrightColors});this.copySnapshot=t,this.copyStatus=void 0,e.blur(),this.updateComplete.then(()=>{let n=this.terminalCopySelector;if(n==null)return;let r=Math.max(0,t.physicalLineCount-e.rows),i=Math.min(r,t.viewportLine);n.scrollTop=(r===0?0:i/r)*Math.max(0,n.scrollHeight-n.clientHeight),this.syncCopySnapshotScroll()})}exitCopyMode(){this.copySnapshot!==void 0&&(this.copySnapshot=void 0,this.copyStatus=void 0)}syncCopySnapshotScroll(){let e=this.terminalCopySelector,t=this.terminalCopyContent;if(e==null||t==null)return;let n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.max(0,t.scrollHeight-t.clientHeight),i=Math.max(0,e.scrollWidth-e.clientWidth),a=Math.max(0,t.scrollWidth-t.clientWidth);t.scrollTop=LO(e.scrollTop,n,r),t.scrollLeft=LO(e.scrollLeft,i,a)}async copyAllSnapshotText(){let e=this.copySnapshot?.text??``;if(e===``){this.copyStatus=`No terminal output to copy.`;return}this.copyStatus=await Oy(e)?`Copied all terminal output.`:`Unable to copy terminal output.`}renderCopyModeToggle(){if(this.selectedId===void 0)return null;let e=this.copySnapshot!==void 0;return g`
5112
5144
  <button
5113
5145
  type="button"
5114
5146
  class=${e?`copy-mode-toggle selected`:`copy-mode-toggle`}
@@ -5131,7 +5163,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5131
5163
  ${this.copyToolbarReplacesSoftKeys()?null:this.renderCopyModeToolbar()}
5132
5164
  <div class="terminal-copy-layers">
5133
5165
  <pre class="terminal-copy-content" aria-hidden="true">${e.lines.map((e,t)=>g`${t===0?null:`
5134
- `}${e.runs.map(e=>g`<span style=${GD(RO(e.style))}>${e.text}</span>`)}`)}</pre>
5166
+ `}${e.runs.map(e=>g`<span style=${KD(zO(e.style))}>${e.text}</span>`)}`)}</pre>
5135
5167
  <textarea
5136
5168
  class="terminal-copy-selector"
5137
5169
  readonly
@@ -5146,7 +5178,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5146
5178
  ></textarea>
5147
5179
  </div>
5148
5180
  </section>
5149
- `}selectedTerminalAcceptsInput(){let e=this.selectedTerminalInfo();return e!==void 0&&!e.exited}copyToolbarReplacesSoftKeys(){return this.copySnapshot!==void 0&&this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}renderTerminalAccessoryBar(){return this.copySnapshot===void 0?this.shouldShowSoftKeys()?this.renderSoftKeys():null:this.copyToolbarReplacesSoftKeys()?this.renderCopyModeToolbar():null}shouldShowSoftKeys(){return this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}shouldShowSoftKeysToggle(){return this.copySnapshot===void 0&&this.selectedTerminalAcceptsInput()}toggleSoftKeys(){this.copySnapshot===void 0&&(this.softKeysEnabled=!this.softKeysEnabled,this.softKeysPreferenceStored=!0,_O(this.softKeysEnabled),this.scheduleFitAndNotify())}renderSoftKeysToggle(){return this.shouldShowSoftKeysToggle()?g`
5181
+ `}selectedTerminalAcceptsInput(){let e=this.selectedTerminalInfo();return e!==void 0&&!e.exited}copyToolbarReplacesSoftKeys(){return this.copySnapshot!==void 0&&this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}renderTerminalAccessoryBar(){return this.copySnapshot===void 0?this.shouldShowSoftKeys()?this.renderSoftKeys():null:this.copyToolbarReplacesSoftKeys()?this.renderCopyModeToolbar():null}shouldShowSoftKeys(){return this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}shouldShowSoftKeysToggle(){return this.copySnapshot===void 0&&this.selectedTerminalAcceptsInput()}toggleSoftKeys(){this.copySnapshot===void 0&&(this.softKeysEnabled=!this.softKeysEnabled,this.softKeysPreferenceStored=!0,vO(this.softKeysEnabled),this.scheduleFitAndNotify())}renderSoftKeysToggle(){return this.shouldShowSoftKeysToggle()?g`
5150
5182
  <button
5151
5183
  type="button"
5152
5184
  class=${this.softKeysEnabled?`soft-keys-toggle selected`:`soft-keys-toggle`}
@@ -5267,32 +5299,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5267
5299
  .error { flex: 0 0 auto; margin: 0; padding: 8px; color: var(--pi-danger); border-bottom: 1px solid var(--pi-border); background: color-mix(in srgb, var(--pi-surface) var(--pi-terminal-ui-opacity, 100%), transparent); }
5268
5300
  .muted { margin: 10px; color: var(--pi-muted); }
5269
5301
  .xterm { height: 100%; }
5270
- `}};B([x({attribute:!1})],Z.prototype,`workspace`,void 0),B([x()],Z.prototype,`machineId`,void 0),B([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),B([x({type:Boolean})],Z.prototype,`autoStart`,void 0),B([x({type:Number})],Z.prototype,`fontSize`,void 0),B([x({type:Number})],Z.prototype,`bgOpacity`,void 0),B([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),B([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),B([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),B([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),B([S()],Z.prototype,`terminals`,void 0),B([S()],Z.prototype,`commandRuns`,void 0),B([S()],Z.prototype,`selectedId`,void 0),B([S()],Z.prototype,`loading`,void 0),B([S()],Z.prototype,`error`,void 0),B([S()],Z.prototype,`visible`,void 0),B([S()],Z.prototype,`cancellingRunIds`,void 0),B([S()],Z.prototype,`continuingTerminalIds`,void 0),B([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),B([S()],Z.prototype,`softKeysEnabled`,void 0),B([S()],Z.prototype,`copySnapshot`,void 0),B([S()],Z.prototype,`copyStatus`,void 0),Z=B([b(`terminal-panel`)],Z);function IO(e,t,n){return t<=0||n<=0?0:Math.min(1,Math.max(0,e/t))*n}function LO(e){return/^#[\da-f]{6}$/i.test(e)?`${e}80`:`color-mix(in srgb, ${e} 50%, transparent)`}function RO(e){let t=[e.underline?`underline`:void 0,e.strikethrough?`line-through`:void 0,e.overline?`overline`:void 0].filter(e=>e!==void 0).join(` `);return{color:e.invisible?`transparent`:e.dim?LO(e.foreground):e.foreground,backgroundColor:e.background,fontWeight:e.bold?`700`:void 0,fontStyle:e.italic?`italic`:void 0,textDecorationLine:t===``?void 0:t}}function zO(e){return e.status===`queued`||e.status===`running`}function BO(e){return e.status===`succeeded`?`Command succeeded${e.exitCode===void 0?``:` with exit code ${String(e.exitCode)}`}`:`Command failed${e.exitCode===void 0?``:` with exit code ${String(e.exitCode)}`}`}function VO(e){let t=JSON.parse(e);if(!ZO(t))return{type:`error`,message:`Invalid terminal message`};let n=t;return n.type===`output`&&typeof n.data==`string`?{type:`output`,data:n.data,...typeof n.replay==`boolean`?{replay:n.replay}:{}}:n.type===`exit`?{type:`exit`,...typeof n.exitCode==`number`?{exitCode:n.exitCode}:{}}:n.type===`error`&&typeof n.message==`string`?{type:`error`,message:n.message}:{type:`error`,message:`Invalid terminal message`}}function HO(e){return e.replaceAll(`\x1B[I`,``).replaceAll(`\x1B[O`,``)}async function UO(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function WO(e){let t=jO;return e instanceof Z?{...t,fontSize:e.fontSize,theme:GO(e)}:{...t,theme:GO(e)}}function GO(e){let t=JO(KO(e,`--pi-terminal-bg`,`#05070a`),e instanceof Z?e.bgOpacity:100);return{...XD,background:t,foreground:KO(e,`--pi-terminal-text`,`#e6edf3`),cursor:KO(e,`--pi-accent`,`#58a6ff`),selectionBackground:KO(e,`--pi-terminal-selection`,`#264f78`)}}function KO(e,t,n){let r=getComputedStyle(e).getPropertyValue(t).trim();return r===``?n:r}function qO(e){return Math.max(0,Math.min(100,e))}function JO(e,t){let n=qO(t)/100;if(n>=1||e===`transparent`)return e;let r=/^#([\da-f]{3}|[\da-f]{6})$/iu.exec(e);if(r===null)return e;let i=r[1]??``,[a=`00`,o=`00`,s=`00`]=i.length===3?[i.charAt(0).repeat(2),i.charAt(1).repeat(2),i.charAt(2).repeat(2)]:[i.slice(0,2),i.slice(2,4),i.slice(4,6)];return`rgba(${String(parseInt(a,16))}, ${String(parseInt(o,16))}, ${String(parseInt(s,16))}, ${String(n)})`}function YO(e){if(!(e===void 0||!XO(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function XO(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function ZO(e){return typeof e==`object`&&!!e}var QO=class extends y{constructor(...e){super(...e),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(){let e=$O(this.machines),t=ek(this.machine),n=nk(this.project),r=ik(this.workspace),i=ok(this.session);return g`
5302
+ `}};B([x({attribute:!1})],Z.prototype,`workspace`,void 0),B([x()],Z.prototype,`machineId`,void 0),B([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),B([x({type:Boolean})],Z.prototype,`autoStart`,void 0),B([x({type:Number})],Z.prototype,`fontSize`,void 0),B([x({type:Number})],Z.prototype,`bgOpacity`,void 0),B([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),B([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),B([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),B([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),B([S()],Z.prototype,`terminals`,void 0),B([S()],Z.prototype,`commandRuns`,void 0),B([S()],Z.prototype,`selectedId`,void 0),B([S()],Z.prototype,`loading`,void 0),B([S()],Z.prototype,`error`,void 0),B([S()],Z.prototype,`visible`,void 0),B([S()],Z.prototype,`cancellingRunIds`,void 0),B([S()],Z.prototype,`continuingTerminalIds`,void 0),B([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),B([S()],Z.prototype,`softKeysEnabled`,void 0),B([S()],Z.prototype,`copySnapshot`,void 0),B([S()],Z.prototype,`copyStatus`,void 0),Z=B([b(`terminal-panel`)],Z);function LO(e,t,n){return t<=0||n<=0?0:Math.min(1,Math.max(0,e/t))*n}function RO(e){return/^#[\da-f]{6}$/i.test(e)?`${e}80`:`color-mix(in srgb, ${e} 50%, transparent)`}function zO(e){let t=[e.underline?`underline`:void 0,e.strikethrough?`line-through`:void 0,e.overline?`overline`:void 0].filter(e=>e!==void 0).join(` `);return{color:e.invisible?`transparent`:e.dim?RO(e.foreground):e.foreground,backgroundColor:e.background,fontWeight:e.bold?`700`:void 0,fontStyle:e.italic?`italic`:void 0,textDecorationLine:t===``?void 0:t}}function BO(e){return e.status===`queued`||e.status===`running`}function VO(e){return e.status===`succeeded`?`Command succeeded${e.exitCode===void 0?``:` with exit code ${String(e.exitCode)}`}`:`Command failed${e.exitCode===void 0?``:` with exit code ${String(e.exitCode)}`}`}function HO(e){let t=JSON.parse(e);if(!QO(t))return{type:`error`,message:`Invalid terminal message`};let n=t;return n.type===`output`&&typeof n.data==`string`?{type:`output`,data:n.data,...typeof n.replay==`boolean`?{replay:n.replay}:{}}:n.type===`exit`?{type:`exit`,...typeof n.exitCode==`number`?{exitCode:n.exitCode}:{}}:n.type===`error`&&typeof n.message==`string`?{type:`error`,message:n.message}:{type:`error`,message:`Invalid terminal message`}}function UO(e){return e.replaceAll(`\x1B[I`,``).replaceAll(`\x1B[O`,``)}async function WO(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function GO(e){let t=MO;return e instanceof Z?{...t,fontSize:e.fontSize,theme:KO(e)}:{...t,theme:KO(e)}}function KO(e){let t=YO(qO(e,`--pi-terminal-bg`,`#05070a`),e instanceof Z?e.bgOpacity:100);return{...ZD,background:t,foreground:qO(e,`--pi-terminal-text`,`#e6edf3`),cursor:qO(e,`--pi-accent`,`#58a6ff`),selectionBackground:qO(e,`--pi-terminal-selection`,`#264f78`)}}function qO(e,t,n){let r=getComputedStyle(e).getPropertyValue(t).trim();return r===``?n:r}function JO(e){return Math.max(0,Math.min(100,e))}function YO(e,t){let n=JO(t)/100;if(n>=1||e===`transparent`)return e;let r=/^#([\da-f]{3}|[\da-f]{6})$/iu.exec(e);if(r===null)return e;let i=r[1]??``,[a=`00`,o=`00`,s=`00`]=i.length===3?[i.charAt(0).repeat(2),i.charAt(1).repeat(2),i.charAt(2).repeat(2)]:[i.slice(0,2),i.slice(2,4),i.slice(4,6)];return`rgba(${String(parseInt(a,16))}, ${String(parseInt(o,16))}, ${String(parseInt(s,16))}, ${String(n)})`}function XO(e){if(!(e===void 0||!ZO(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function ZO(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function QO(e){return typeof e==`object`&&!!e}var $O=class extends y{constructor(...e){super(...e),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(){let e=ek(this.machines),t=tk(this.machine),n=rk(this.project),r=ak(this.workspace),i=sk(this.session);return g`
5271
5303
  <nav class=${this.contextBarClass()} aria-label="Current location">
5272
5304
  <span class="context-bar-label">Location</span>
5273
5305
  <ol class="context-items" @scroll=${this.onContextScroll}>
5274
5306
  ${e?g`
5275
5307
  <li class="context-item">
5276
- <button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${tk(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
5308
+ <button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${nk(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
5277
5309
  <span class="context-kind">Machine</span>
5278
5310
  <span class="context-value">${t}</span>
5279
5311
  </button>
5280
5312
  </li>
5281
5313
  `:null}
5282
5314
  <li class="context-item">
5283
- <button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${rk(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
5315
+ <button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${ik(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
5284
5316
  <span class="context-kind">Project</span>
5285
5317
  <span class="context-value">${n}</span>
5286
5318
  </button>
5287
5319
  </li>
5288
5320
  <li class="context-item">
5289
- <button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${ak(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
5321
+ <button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${ok(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
5290
5322
  <span class="context-kind">Workspace</span>
5291
5323
  <span class="context-value">${r}</span>
5292
5324
  </button>
5293
5325
  </li>
5294
5326
  <li class="context-item">
5295
- <button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${sk(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
5327
+ <button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${ck(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
5296
5328
  <span class="context-kind">Session</span>
5297
5329
  <span class="context-value">${i}</span>
5298
5330
  </button>
@@ -5332,7 +5364,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5332
5364
  .context-kind { display: none; }
5333
5365
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
5334
5366
  button { cursor: pointer; }
5335
- `}};B([x({attribute:!1})],QO.prototype,`machines`,void 0),B([x({attribute:!1})],QO.prototype,`machine`,void 0),B([x({attribute:!1})],QO.prototype,`project`,void 0),B([x({attribute:!1})],QO.prototype,`workspace`,void 0),B([x({attribute:!1})],QO.prototype,`session`,void 0),B([x({attribute:!1})],QO.prototype,`refreshControl`,void 0),B([x({attribute:!1})],QO.prototype,`onOpenSection`,void 0),B([x({attribute:!1})],QO.prototype,`onShowActions`,void 0),B([C(`.context-items`)],QO.prototype,`contextItems`,void 0),B([S()],QO.prototype,`canScrollLeft`,void 0),B([S()],QO.prototype,`canScrollRight`,void 0),QO=B([b(`app-context-bar`)],QO);function $O(e){return e.length>1}function ek(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function tk(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function nk(e){return e?.name??`No project`}function rk(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function ik(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function ak(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function ok(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?`No session`:hv(e.id)}function sk(e){return e===void 0?`No session selected`:e.path}var ck=class extends y{constructor(...e){super(...e),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(){let e=this.fallbackLabels();return g`
5367
+ `}};B([x({attribute:!1})],$O.prototype,`machines`,void 0),B([x({attribute:!1})],$O.prototype,`machine`,void 0),B([x({attribute:!1})],$O.prototype,`project`,void 0),B([x({attribute:!1})],$O.prototype,`workspace`,void 0),B([x({attribute:!1})],$O.prototype,`session`,void 0),B([x({attribute:!1})],$O.prototype,`refreshControl`,void 0),B([x({attribute:!1})],$O.prototype,`onOpenSection`,void 0),B([x({attribute:!1})],$O.prototype,`onShowActions`,void 0),B([C(`.context-items`)],$O.prototype,`contextItems`,void 0),B([S()],$O.prototype,`canScrollLeft`,void 0),B([S()],$O.prototype,`canScrollRight`,void 0),$O=B([b(`app-context-bar`)],$O);function ek(e){return e.length>1}function tk(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function nk(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function rk(e){return e?.name??`No project`}function ik(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function ak(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function ok(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function sk(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?`No session`:hv(e.id)}function ck(e){return e===void 0?`No session selected`:e.path}var lk=class extends y{constructor(...e){super(...e),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(){let e=this.fallbackLabels();return g`
5336
5368
  <div class=${this.frameClass()}>
5337
5369
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
5338
5370
  ${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
@@ -5371,12 +5403,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5371
5403
  .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; }
5372
5404
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
5373
5405
  }
5374
- `}};B([x({attribute:!1})],ck.prototype,`tabs`,void 0),B([x({attribute:!1})],ck.prototype,`selectedView`,void 0),B([x({attribute:!1})],ck.prototype,`onSelect`,void 0),B([C(`.mobile-tabs`)],ck.prototype,`mobileTabs`,void 0),B([S()],ck.prototype,`canScrollLeft`,void 0),B([S()],ck.prototype,`canScrollRight`,void 0),ck=B([b(`app-mobile-main-tabs`)],ck);var lk=class extends y{constructor(...e){super(...e),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(e=>e.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){let e=this.switcherButton();return e!==null&&await this.openMenuAndFocusOption(e)}render(){let e=this.selectedMachine();if(e===void 0)return null;let t=uk(e,this.statuses),n=e.name;return g`
5406
+ `}};B([x({attribute:!1})],lk.prototype,`tabs`,void 0),B([x({attribute:!1})],lk.prototype,`selectedView`,void 0),B([x({attribute:!1})],lk.prototype,`onSelect`,void 0),B([C(`.mobile-tabs`)],lk.prototype,`mobileTabs`,void 0),B([S()],lk.prototype,`canScrollLeft`,void 0),B([S()],lk.prototype,`canScrollRight`,void 0),lk=B([b(`app-mobile-main-tabs`)],lk);var uk=class extends y{constructor(...e){super(...e),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(e=>e.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){let e=this.switcherButton();return e!==null&&await this.openMenuAndFocusOption(e)}render(){let e=this.selectedMachine();if(e===void 0)return null;let t=dk(e,this.statuses),n=e.name;return g`
5375
5407
  <div class="machine-switcher">
5376
5408
  <button
5377
5409
  type="button"
5378
5410
  class="machine-switcher-button"
5379
- title=${fk(e)}
5411
+ title=${pk(e)}
5380
5412
  aria-label=${this.machineSwitcherAriaLabel(e)}
5381
5413
  aria-expanded=${String(this.open)}
5382
5414
  @click=${e=>{this.toggleMenu(e.currentTarget)}}
@@ -5387,7 +5419,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5387
5419
  <span class="machine-switcher-kicker">Machine</span>
5388
5420
  <span class="machine-switcher-label">${n}</span>
5389
5421
  </span>
5390
- <span class=${`machine-status ${t}`}>${dk(t)}</span>
5422
+ <span class=${`machine-status ${t}`}>${fk(t)}</span>
5391
5423
  <span class="machine-chevron" aria-hidden="true">▾</span>
5392
5424
  </button>
5393
5425
  ${this.open?g`
@@ -5396,18 +5428,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5396
5428
  </div>
5397
5429
  `:null}
5398
5430
  </div>
5399
- `}renderMachineOption(e){let t=this.selected?.id===e.id,n=uk(e,this.statuses),r=z_(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
5431
+ `}renderMachineOption(e){let t=this.selected?.id===e.id,n=dk(e,this.statuses),r=z_(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
5400
5432
  <div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
5401
5433
  <button
5402
5434
  type="button"
5403
5435
  class="machine-option-main"
5404
- title=${fk(e)}
5436
+ title=${pk(e)}
5405
5437
  data-machine-id=${e.id}
5406
5438
  @click=${()=>{this.select(e)}}
5407
5439
  @keydown=${e=>{this.handleMachineOptionKeydown(e)}}
5408
5440
  >
5409
5441
  <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
5410
- <small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${dk(n)}</small>
5442
+ <small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${fk(n)}</small>
5411
5443
  </button>
5412
5444
  ${r?g`
5413
5445
  <div class="machine-option-actions">
@@ -5427,7 +5459,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5427
5459
  </div>
5428
5460
  `:null}
5429
5461
  </div>
5430
- `}renderActivity(e){let t=uk(e,this.statuses);if(t===`offline`||t===`error`)return;let n=qs(this.activities[e.id]);return S_(n,n===`terminal`?`Machine terminal active`:`Machine active`)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`Machine: ${e.name}. Switch machine.`}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=pk(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){let e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=pk(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){let e=this.renderRoot.querySelector(`.machine-option.selected .machine-option-main`),t=this.machineOptionButtons()[0],n=e??t;return n===void 0?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}focusRelativeMachineOption(e,t,n){n.preventDefault(),n.stopPropagation();let r=this.machineOptionButtons();if(r.length===0||!(e instanceof HTMLElement))return;let i=r.indexOf(e);i<0||this.focusMachineOptionAt(i+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){let t=this.machineOptionButtons(),n=t[Math.min(Math.max(e,0),t.length-1)];n?.focus(),n?.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=v_(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)}static{this.styles=h`
5462
+ `}renderActivity(e){let t=dk(e,this.statuses);if(t===`offline`||t===`error`)return;let n=qs(this.activities[e.id]);return S_(n,n===`terminal`?`Machine terminal active`:`Machine active`)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`Machine: ${e.name}. Switch machine.`}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=mk(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){let e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=mk(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){let e=this.renderRoot.querySelector(`.machine-option.selected .machine-option-main`),t=this.machineOptionButtons()[0],n=e??t;return n===void 0?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}focusRelativeMachineOption(e,t,n){n.preventDefault(),n.stopPropagation();let r=this.machineOptionButtons();if(r.length===0||!(e instanceof HTMLElement))return;let i=r.indexOf(e);i<0||this.focusMachineOptionAt(i+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){let t=this.machineOptionButtons(),n=t[Math.min(Math.max(e,0),t.length-1)];n?.focus(),n?.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=v_(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)}static{this.styles=h`
5431
5463
  :host { min-width: 0; display: block; }
5432
5464
  .machine-switcher { min-width: 0; }
5433
5465
  .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; }
@@ -5460,10 +5492,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5460
5492
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
5461
5493
  .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); }
5462
5494
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
5463
- `}};B([x({attribute:!1})],lk.prototype,`machines`,void 0),B([x({attribute:!1})],lk.prototype,`selected`,void 0),B([x({attribute:!1})],lk.prototype,`statuses`,void 0),B([x({attribute:!1})],lk.prototype,`activities`,void 0),B([x({attribute:!1})],lk.prototype,`onSelect`,void 0),B([x({attribute:!1})],lk.prototype,`onRemove`,void 0),B([x({attribute:!1})],lk.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],lk.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],lk.prototype,`open`,void 0),B([S()],lk.prototype,`menuStyle`,void 0),B([S()],lk.prototype,`openActionsMachineId`,void 0),B([S()],lk.prototype,`actionMenuStyle`,void 0),lk=B([b(`machine-switcher`)],lk);function uk(e,t){return t[e.id]?.status??e.status??`unknown`}function dk(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function fk(e){return e.baseUrl??e.name}function pk(e){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let t=e.getBoundingClientRect(),n=Math.min(280,Math.max(0,window.innerWidth-16)),r=Math.min(Math.max(8,t.left),Math.max(8,window.innerWidth-8-n)),i=Math.max(0,window.innerHeight-t.bottom-8);return[`top: ${mk(t.bottom)};`,`left: ${mk(r)};`,`width: ${mk(n)};`,`max-height: ${mk(i)};`].join(` `)}function mk(e){return`${String(Math.round(e))}px`}var hk=[{id:`models`,label:`Models`},{id:`skills`,label:`Skills`},{id:`plugins`,label:`Plugins`}],Q=class extends y{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.projectSessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`Update and restart Pi-Web on this machine to delete archived sessions.`,this.cleanupUnavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.skillsEnabled=!1,this.pluginsEnabled=!1}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(){let e=this.version;return g`
5495
+ `}};B([x({attribute:!1})],uk.prototype,`machines`,void 0),B([x({attribute:!1})],uk.prototype,`selected`,void 0),B([x({attribute:!1})],uk.prototype,`statuses`,void 0),B([x({attribute:!1})],uk.prototype,`activities`,void 0),B([x({attribute:!1})],uk.prototype,`onSelect`,void 0),B([x({attribute:!1})],uk.prototype,`onRemove`,void 0),B([x({attribute:!1})],uk.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],uk.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],uk.prototype,`open`,void 0),B([S()],uk.prototype,`menuStyle`,void 0),B([S()],uk.prototype,`openActionsMachineId`,void 0),B([S()],uk.prototype,`actionMenuStyle`,void 0),uk=B([b(`machine-switcher`)],uk);function dk(e,t){return t[e.id]?.status??e.status??`unknown`}function fk(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function pk(e){return e.baseUrl??e.name}function mk(e){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let t=e.getBoundingClientRect(),n=Math.min(280,Math.max(0,window.innerWidth-16)),r=Math.min(Math.max(8,t.left),Math.max(8,window.innerWidth-8-n)),i=Math.max(0,window.innerHeight-t.bottom-8);return[`top: ${hk(t.bottom)};`,`left: ${hk(r)};`,`width: ${hk(n)};`,`max-height: ${hk(i)};`].join(` `)}function hk(e){return`${String(Math.round(e))}px`}var gk=[{id:`models`,label:`Models`},{id:`skills`,label:`Skills`},{id:`plugins`,label:`Plugins`}],Q=class extends y{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.projectSessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`Update and restart Pi-Web on this machine to delete archived sessions.`,this.cleanupUnavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.skillsEnabled=!1,this.pluginsEnabled=!1}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(){let e=this.version;return g`
5464
5496
  <header>
5465
5497
  <strong class="brand" aria-label=${e===void 0?`Pi WebUI`:`Pi WebUI version ${e}`}><span class="brand-symbol" aria-hidden="true">π</span><span>WebUI</span>${e===void 0?null:g`<span class="brand-version">v${e}</span>`}</strong>
5466
- ${yk(this.machines)?g`
5498
+ ${bk(this.machines)?g`
5467
5499
  <machine-switcher
5468
5500
  .machines=${this.machines}
5469
5501
  .selected=${this.selectedMachine}
@@ -5480,7 +5512,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5480
5512
  <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
5481
5513
  </div>
5482
5514
  </header>
5483
- ${this.compact&&yk(this.machines)?g`
5515
+ ${this.compact&&bk(this.machines)?g`
5484
5516
  <machine-list
5485
5517
  .machines=${this.machines}
5486
5518
  .selected=${this.selectedMachine}
@@ -5570,9 +5602,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5570
5602
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
5571
5603
  ></session-list>
5572
5604
  <footer class="resource-underbar" aria-label="Resources">
5573
- ${hk.map(e=>gk(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
5605
+ ${gk.map(e=>_k(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
5574
5606
  </footer>
5575
- `}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=bk(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(xk(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
5607
+ `}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=xk(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Sk(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
5576
5608
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
5577
5609
  :host([compact]) { flex: 1 1 auto; }
5578
5610
  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); }
@@ -5604,12 +5636,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5604
5636
  :host([compact]) workspace-list[collapsed],
5605
5637
  :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
5606
5638
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
5607
- `}};B([x({attribute:!1})],Q.prototype,`machines`,void 0),B([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),B([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),B([x({attribute:!1})],Q.prototype,`projects`,void 0),B([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),B([x({attribute:!1})],Q.prototype,`workspaces`,void 0),B([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`sessions`,void 0),B([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),B([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),B([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),B([x({type:String})],Q.prototype,`version`,void 0),B([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),B([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),B([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),B([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),B([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),B([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),B([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),B([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),B([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),B([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),B([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSessionBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),B([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),B([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),B([C(`machine-list`)],Q.prototype,`machineList`,void 0),B([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),B([C(`project-list`)],Q.prototype,`projectList`,void 0),B([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),B([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=B([b(`app-navigation-panel`)],Q);function gk(e,t,n,r){return g`
5608
- <button type="button" ?disabled=${!_k(e.id,n,r)} title=${e.label} aria-label=${e.label} @click=${t}>
5609
- ${vk(e.id)}
5639
+ `}};B([x({attribute:!1})],Q.prototype,`machines`,void 0),B([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),B([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),B([x({attribute:!1})],Q.prototype,`projects`,void 0),B([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),B([x({attribute:!1})],Q.prototype,`workspaces`,void 0),B([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`sessions`,void 0),B([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),B([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),B([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),B([x({type:String})],Q.prototype,`version`,void 0),B([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),B([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),B([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),B([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),B([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),B([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),B([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),B([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),B([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),B([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),B([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSessionBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),B([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),B([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),B([C(`machine-list`)],Q.prototype,`machineList`,void 0),B([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),B([C(`project-list`)],Q.prototype,`projectList`,void 0),B([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),B([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=B([b(`app-navigation-panel`)],Q);function _k(e,t,n,r){return g`
5640
+ <button type="button" ?disabled=${!vk(e.id,n,r)} title=${e.label} aria-label=${e.label} @click=${t}>
5641
+ ${yk(e.id)}
5610
5642
  <span>${e.label}</span>
5611
5643
  </button>
5612
- `}function _k(e,t=!1,n=t){return e===`models`||e===`skills`&&t||e===`plugins`&&n}function vk(e){switch(e){case`models`:return _`
5644
+ `}function vk(e,t=!1,n=t){return e===`models`||e===`skills`&&t||e===`plugins`&&n}function yk(e){switch(e){case`models`:return _`
5613
5645
  <svg class="resource-underbar-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
5614
5646
  <rect x="4" y="4" width="16" height="16" rx="2"></rect>
5615
5647
  <rect x="9" y="9" width="6" height="6"></rect>
@@ -5627,7 +5659,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5627
5659
  <path d="M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0Z"></path>
5628
5660
  <path d="M12 19v3"></path>
5629
5661
  </svg>
5630
- `}}function yk(e){return e.length>1}function bk(e,t){let n=Sk(t);return n[n.indexOf(e)-1]}function xk(e,t){let n=Sk(t);return n[n.indexOf(e)+1]??`chat`}function Sk(e){return eg.filter(t=>t!==`machines`||yk(e))}var Ck=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),wk=420,Tk=4,Ek=class extends y{constructor(...e){super(...e),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(){let e=this.collapsed?this.expandLabel:this.collapseLabel;return g`
5662
+ `}}function bk(e){return e.length>1}function xk(e,t){let n=Ck(t);return n[n.indexOf(e)-1]}function Sk(e,t){let n=Ck(t);return n[n.indexOf(e)+1]??`chat`}function Ck(e){return eg.filter(t=>t!==`machines`||bk(e))}var wk=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),Tk=420,Ek=4,Dk=class extends y{constructor(...e){super(...e),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(){let e=this.collapsed?this.expandLabel:this.collapseLabel;return g`
5631
5663
  ${this.renderResizeHandle()}
5632
5664
  <button
5633
5665
  type="button"
@@ -5657,7 +5689,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5657
5689
  @dblclick=${e=>{this.onResizeDoubleClick(e)}}
5658
5690
  @keydown=${e=>{this.onResizeKeyDown(e)}}
5659
5691
  ></div>
5660
- `}resizeAriaValueNow(){return this.panelWidth===void 0?v:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=Tk)&&(t.moved=!0,this.commitPanelWidth(vg(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){let 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||!Ck.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=yg(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});n!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(n),this.onResizeEnd?.())}registerTapForReset(){let e=Date.now();if(e-this.lastTapAt<=wk){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){let e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return bg(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(bg(this.side,e,this.resizeConstraints()))}finishActiveResize(){let 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(){let e=gg(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
5692
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?v:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=Ek)&&(t.moved=!0,this.commitPanelWidth(vg(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){let 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||!wk.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=yg(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});n!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(n),this.onResizeEnd?.())}registerTapForReset(){let e=Date.now();if(e-this.lastTapAt<=Tk){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){let e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return bg(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(bg(this.side,e,this.resizeConstraints()))}finishActiveResize(){let 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(){let e=gg(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
5661
5693
  :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; }
5662
5694
  :host([side="navigation"]) { grid-column: 2; }
5663
5695
  :host([side="workspace"]) { grid-column: 4; }
@@ -5676,7 +5708,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5676
5708
  @media (max-width: 760px) {
5677
5709
  :host([side="navigation"]) { display: none; }
5678
5710
  }
5679
- `}};B([x({reflect:!0})],Ek.prototype,`side`,void 0),B([x({type:Boolean,reflect:!0})],Ek.prototype,`collapsed`,void 0),B([x({type:Boolean})],Ek.prototype,`resizable`,void 0),B([x({type:Number})],Ek.prototype,`panelWidth`,void 0),B([x({type:Number})],Ek.prototype,`minWidth`,void 0),B([x({type:Number})],Ek.prototype,`maxWidth`,void 0),B([x()],Ek.prototype,`controls`,void 0),B([x()],Ek.prototype,`resizeLabel`,void 0),B([x()],Ek.prototype,`expandLabel`,void 0),B([x()],Ek.prototype,`collapseLabel`,void 0),B([x({attribute:!1})],Ek.prototype,`onToggle`,void 0),B([x({attribute:!1})],Ek.prototype,`onResizeStart`,void 0),B([x({attribute:!1})],Ek.prototype,`onResize`,void 0),B([x({attribute:!1})],Ek.prototype,`onResizeEnd`,void 0),B([x({attribute:!1})],Ek.prototype,`onReset`,void 0),Ek=B([b(`app-panel-edge-control`)],Ek);var Dk=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
5711
+ `}};B([x({reflect:!0})],Dk.prototype,`side`,void 0),B([x({type:Boolean,reflect:!0})],Dk.prototype,`collapsed`,void 0),B([x({type:Boolean})],Dk.prototype,`resizable`,void 0),B([x({type:Number})],Dk.prototype,`panelWidth`,void 0),B([x({type:Number})],Dk.prototype,`minWidth`,void 0),B([x({type:Number})],Dk.prototype,`maxWidth`,void 0),B([x()],Dk.prototype,`controls`,void 0),B([x()],Dk.prototype,`resizeLabel`,void 0),B([x()],Dk.prototype,`expandLabel`,void 0),B([x()],Dk.prototype,`collapseLabel`,void 0),B([x({attribute:!1})],Dk.prototype,`onToggle`,void 0),B([x({attribute:!1})],Dk.prototype,`onResizeStart`,void 0),B([x({attribute:!1})],Dk.prototype,`onResize`,void 0),B([x({attribute:!1})],Dk.prototype,`onResizeEnd`,void 0),B([x({attribute:!1})],Dk.prototype,`onReset`,void 0),Dk=B([b(`app-panel-edge-control`)],Dk);var Ok=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
5680
5712
  <button
5681
5713
  class="app-refresh-button"
5682
5714
  title=${e}
@@ -5695,7 +5727,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5695
5727
  :host, :host * { -webkit-user-select: none; user-select: none; }
5696
5728
  .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; }
5697
5729
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
5698
- `}};B([x({attribute:!1})],Dk.prototype,`onReload`,void 0),Dk=B([b(`app-refresh-control`)],Dk);var Ok=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],kk=`file-manager`,Ak=`browser`,jk=[...Ok],Mk=new Set(Ok),Nk=`pi-webui:activity-rail-order`;function Pk(){return typeof localStorage>`u`?void 0:localStorage}function Fk(e){return Mk.has(e)}function Ik(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===kk?`git-update-manager`:r;if(e!==Ak){if(!Fk(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===Ok.length)return t;let r=[...t];if(!n.has(`git-update-manager`)){let e=r.indexOf(`terminal`);r.splice(e+1,0,`git-update-manager`)}return n.has(`info`)||r.push(`info`),r.length===Ok.length?r:void 0}function Lk(){try{let e=Pk();if(e===void 0)return;let t=e.getItem(Nk);return t===null?void 0:Ik(JSON.parse(t))}catch{return}}function Rk(e){try{let t=Pk();if(t===void 0)return;t.setItem(Nk,JSON.stringify(e))}catch{}}var zk=`(min-width: 1181px)`,Bk=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function Vk(e){return Bk.includes(e)}var Hk=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...jk],this.onDesktopMediaChange=()=>{},this.openTerminal=()=>{this.onOpenTerminal?.()},this.openGitUpdateManager=()=>{this.onOpenGitUpdateManager?.()},this.openTheme=()=>{this.onOpenTheme?.()},this.openSystemPrompt=()=>{this.onOpenSystemPrompt?.()},this.openHistory=()=>{this.onOpenHistory?.()},this.openInfo=()=>{this.onOpenInfo?.()},this.openSettings=()=>{this.onOpenSettings?.()},this.onDragStart=(e,t)=>{this.dragItem=e,t.dataTransfer!==null&&(t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,e)),requestAnimationFrame(()=>{this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.add(`dragging`)})},this.onDragEnd=e=>{this.dragItem=void 0,this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.remove(`dragging`),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)})},this.onRailDragOver=e=>{if(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`move`),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),t!==null&&t.dataset.railItem!==this.dragItem&&t.classList.add(`drag-over`)},this.onRailDrop=e=>{if(e.preventDefault(),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);if(t===null||t.dataset.railItem===this.dragItem){this.dragItem=void 0;return}let n=t.dataset.railItem;if(n===void 0||!Vk(n)){this.dragItem=void 0;return}let r=[...this.railOrder],i=r.indexOf(this.dragItem),a=r.indexOf(n);if(i===-1||a===-1){this.dragItem=void 0;return}r.splice(i,1),r.splice(a,0,this.dragItem),this.railOrder=r,this.onRailOrderChange?.(r),this.dragItem=void 0},typeof window<`u`&&`matchMedia`in window&&(this.desktopMedia=window.matchMedia(zk))}connectedCallback(){super.connectedCallback(),this.desktopMedia?.addEventListener(`change`,this.onDesktopMediaChange)}disconnectedCallback(){super.disconnectedCallback(),this.desktopMedia?.removeEventListener(`change`,this.onDesktopMediaChange)}resolveDragTarget(e){if(e===null||!(e instanceof HTMLElement))return null;let t=e.closest(`[data-rail-item]`);return t instanceof HTMLElement?t:null}dndProps(e){return{draggable:`true`,"data-rail-item":e}}renderReorderableButton(e){switch(e){case`terminal`:return this.renderTerminalButton();case`git-update-manager`:return this.renderGitUpdateManagerButton();case`theme`:return this.renderThemeButton();case`system-prompt`:return this.renderSystemPromptButton();case`history`:return this.renderHistoryButton();case`info`:return this.renderInfoButton()}}renderTerminalButton(){let e=this.dndProps(`terminal`),t=this.terminalCount>0?this.terminalCount:void 0,n=t===void 0?``:`${String(t)} active terminal${t===1?``:`s`}`;return g`
5730
+ `}};B([x({attribute:!1})],Ok.prototype,`onReload`,void 0),Ok=B([b(`app-refresh-control`)],Ok);var kk=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],Ak=`file-manager`,jk=`browser`,Mk=[...kk],Nk=new Set(kk),Pk=`pi-webui:activity-rail-order`;function Fk(){return typeof localStorage>`u`?void 0:localStorage}function Ik(e){return Nk.has(e)}function Lk(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===Ak?`git-update-manager`:r;if(e!==jk){if(!Ik(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===kk.length)return t;let r=[...t];if(!n.has(`git-update-manager`)){let e=r.indexOf(`terminal`);r.splice(e+1,0,`git-update-manager`)}return n.has(`info`)||r.push(`info`),r.length===kk.length?r:void 0}function Rk(){try{let e=Fk();if(e===void 0)return;let t=e.getItem(Pk);return t===null?void 0:Lk(JSON.parse(t))}catch{return}}function zk(e){try{let t=Fk();if(t===void 0)return;t.setItem(Pk,JSON.stringify(e))}catch{}}var Bk=`(min-width: 1181px)`,Vk=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function Hk(e){return Vk.includes(e)}var Uk=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...Mk],this.onDesktopMediaChange=()=>{},this.openTerminal=()=>{this.onOpenTerminal?.()},this.openGitUpdateManager=()=>{this.onOpenGitUpdateManager?.()},this.openTheme=()=>{this.onOpenTheme?.()},this.openSystemPrompt=()=>{this.onOpenSystemPrompt?.()},this.openHistory=()=>{this.onOpenHistory?.()},this.openInfo=()=>{this.onOpenInfo?.()},this.openSettings=()=>{this.onOpenSettings?.()},this.onDragStart=(e,t)=>{this.dragItem=e,t.dataTransfer!==null&&(t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,e)),requestAnimationFrame(()=>{this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.add(`dragging`)})},this.onDragEnd=e=>{this.dragItem=void 0,this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.remove(`dragging`),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)})},this.onRailDragOver=e=>{if(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`move`),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),t!==null&&t.dataset.railItem!==this.dragItem&&t.classList.add(`drag-over`)},this.onRailDrop=e=>{if(e.preventDefault(),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);if(t===null||t.dataset.railItem===this.dragItem){this.dragItem=void 0;return}let n=t.dataset.railItem;if(n===void 0||!Hk(n)){this.dragItem=void 0;return}let r=[...this.railOrder],i=r.indexOf(this.dragItem),a=r.indexOf(n);if(i===-1||a===-1){this.dragItem=void 0;return}r.splice(i,1),r.splice(a,0,this.dragItem),this.railOrder=r,this.onRailOrderChange?.(r),this.dragItem=void 0},typeof window<`u`&&`matchMedia`in window&&(this.desktopMedia=window.matchMedia(Bk))}connectedCallback(){super.connectedCallback(),this.desktopMedia?.addEventListener(`change`,this.onDesktopMediaChange)}disconnectedCallback(){super.disconnectedCallback(),this.desktopMedia?.removeEventListener(`change`,this.onDesktopMediaChange)}resolveDragTarget(e){if(e===null||!(e instanceof HTMLElement))return null;let t=e.closest(`[data-rail-item]`);return t instanceof HTMLElement?t:null}dndProps(e){return{draggable:`true`,"data-rail-item":e}}renderReorderableButton(e){switch(e){case`terminal`:return this.renderTerminalButton();case`git-update-manager`:return this.renderGitUpdateManagerButton();case`theme`:return this.renderThemeButton();case`system-prompt`:return this.renderSystemPromptButton();case`history`:return this.renderHistoryButton();case`info`:return this.renderInfoButton()}}renderTerminalButton(){let e=this.dndProps(`terminal`),t=this.terminalCount>0?this.terminalCount:void 0,n=t===void 0?``:`${String(t)} active terminal${t===1?``:`s`}`;return g`
5699
5731
  <button
5700
5732
  type="button"
5701
5733
  class="icon-button terminal-button"
@@ -5835,7 +5867,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5835
5867
  <circle cx="12" cy="12" r="3"/>
5836
5868
  </svg>
5837
5869
  </button>
5838
- `}render(){if(!(this.desktopMedia?.matches??!0))return g``;let e=this.railOrder.length===0?[...jk]:this.railOrder;return g`
5870
+ `}render(){if(!(this.desktopMedia?.matches??!0))return g``;let e=this.railOrder.length===0?[...Mk]:this.railOrder;return g`
5839
5871
  <nav
5840
5872
  class="rail"
5841
5873
  aria-label="Activity rail"
@@ -5909,7 +5941,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5909
5941
  }
5910
5942
  .rail-spacer { flex: 1 1 auto; min-height: 0; }
5911
5943
  .settings-button { margin-bottom: 12px; }
5912
- `}};B([x({attribute:!1})],Hk.prototype,`onOpenTerminal`,void 0),B([x({attribute:!1})],Hk.prototype,`onOpenGitUpdateManager`,void 0),B([x({attribute:!1})],Hk.prototype,`onOpenTheme`,void 0),B([x({attribute:!1})],Hk.prototype,`onOpenSystemPrompt`,void 0),B([x({attribute:!1})],Hk.prototype,`onOpenHistory`,void 0),B([x({attribute:!1})],Hk.prototype,`onOpenInfo`,void 0),B([x({attribute:!1})],Hk.prototype,`onOpenSettings`,void 0),B([x({type:Number})],Hk.prototype,`terminalCount`,void 0),B([x({type:Number})],Hk.prototype,`gitUpdateManagerCount`,void 0),B([x({type:Boolean})],Hk.prototype,`systemPromptEnabled`,void 0),B([x({type:Boolean})],Hk.prototype,`historyEnabled`,void 0),B([x({attribute:!1})],Hk.prototype,`railOrder`,void 0),B([x({attribute:!1})],Hk.prototype,`onRailOrderChange`,void 0),Hk=B([b(`activity-rail`)],Hk);var Uk=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.api=go,this.loadingStatus=!1,this.loadingDiff=!1,this.error=``,this.statusRequest=0,this.diffRequest=0,this.refresh=async()=>{let e=this.workspace;if(e===void 0)return;let t=this.machineId,n=this.selectedChange?.id,r=++this.statusRequest;this.diffRequest+=1,this.status=void 0,this.selectedDiff=void 0,this.loadingStatus=!0,this.loadingDiff=!1,this.error=``;try{let i=await this.api.gitStatus(e.projectId,e.id,t);if(r!==this.statusRequest||!this.isCurrentWorkspace(e,t))return;this.status=i,this.loadingStatus=!1,this.onStatusChange?.(i);let a=n===void 0?void 0:Gk(i,n);this.selectedChange=a,a!==void 0&&await this.loadDiff(a,e,t)}catch(n){if(r!==this.statusRequest||!this.isCurrentWorkspace(e,t))return;this.status=void 0,this.selectedChange=void 0,this.selectedDiff=void 0,this.loadingStatus=!1,this.error=Jk(n)}},this.selectChange=e=>{let t=this.workspace;if(t===void 0)return;let n=this.machineId;this.selectedChange=e,this.selectedDiff=void 0,this.error=``,this.loadDiff(e,t,n)},this.onViewportResize=()=>{this.bounds!==void 0&&(this.bounds=$g(this.bounds,this.viewport()))},this.handleMovePointerDown=e=>{this.startPointerInteraction(`move`,e)},this.handleResizePointerDown=e=>{this.startPointerInteraction(`resize`,e)},this.handlePointerMove=e=>{let t=this.pointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY};this.bounds=t.operation===`move`?Zg(t.bounds,n,this.viewport()):Qg(t.bounds,n,this.viewport())},this.handlePointerUp=e=>{this.pointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishPointerInteraction())},this.handlePointerCancel=e=>{this.pointerInteraction?.pointerId===e.pointerId&&this.finishPointerInteraction()},this.close=()=>{this.finishPointerInteraction(),this.onClose?.()}}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),this.ensureWorkspaceScope()}willUpdate(){this.ensureWorkspaceScope()}disconnectedCallback(){this.finishPointerInteraction(),this.statusRequest+=1,this.diffRequest+=1,window.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}render(){return g`
5944
+ `}};B([x({attribute:!1})],Uk.prototype,`onOpenTerminal`,void 0),B([x({attribute:!1})],Uk.prototype,`onOpenGitUpdateManager`,void 0),B([x({attribute:!1})],Uk.prototype,`onOpenTheme`,void 0),B([x({attribute:!1})],Uk.prototype,`onOpenSystemPrompt`,void 0),B([x({attribute:!1})],Uk.prototype,`onOpenHistory`,void 0),B([x({attribute:!1})],Uk.prototype,`onOpenInfo`,void 0),B([x({attribute:!1})],Uk.prototype,`onOpenSettings`,void 0),B([x({type:Number})],Uk.prototype,`terminalCount`,void 0),B([x({type:Number})],Uk.prototype,`gitUpdateManagerCount`,void 0),B([x({type:Boolean})],Uk.prototype,`systemPromptEnabled`,void 0),B([x({type:Boolean})],Uk.prototype,`historyEnabled`,void 0),B([x({attribute:!1})],Uk.prototype,`railOrder`,void 0),B([x({attribute:!1})],Uk.prototype,`onRailOrderChange`,void 0),Uk=B([b(`activity-rail`)],Uk);var Wk=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.api=go,this.loadingStatus=!1,this.loadingDiff=!1,this.error=``,this.statusRequest=0,this.diffRequest=0,this.refresh=async()=>{let e=this.workspace;if(e===void 0)return;let t=this.machineId,n=this.selectedChange?.id,r=++this.statusRequest;this.diffRequest+=1,this.status=void 0,this.selectedDiff=void 0,this.loadingStatus=!0,this.loadingDiff=!1,this.error=``;try{let i=await this.api.gitStatus(e.projectId,e.id,t);if(r!==this.statusRequest||!this.isCurrentWorkspace(e,t))return;this.status=i,this.loadingStatus=!1,this.onStatusChange?.(i);let a=n===void 0?void 0:Kk(i,n);this.selectedChange=a,a!==void 0&&await this.loadDiff(a,e,t)}catch(n){if(r!==this.statusRequest||!this.isCurrentWorkspace(e,t))return;this.status=void 0,this.selectedChange=void 0,this.selectedDiff=void 0,this.loadingStatus=!1,this.error=Yk(n)}},this.selectChange=e=>{let t=this.workspace;if(t===void 0)return;let n=this.machineId;this.selectedChange=e,this.selectedDiff=void 0,this.error=``,this.loadDiff(e,t,n)},this.onViewportResize=()=>{this.bounds!==void 0&&(this.bounds=$g(this.bounds,this.viewport()))},this.handleMovePointerDown=e=>{this.startPointerInteraction(`move`,e)},this.handleResizePointerDown=e=>{this.startPointerInteraction(`resize`,e)},this.handlePointerMove=e=>{let t=this.pointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY};this.bounds=t.operation===`move`?Zg(t.bounds,n,this.viewport()):Qg(t.bounds,n,this.viewport())},this.handlePointerUp=e=>{this.pointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishPointerInteraction())},this.handlePointerCancel=e=>{this.pointerInteraction?.pointerId===e.pointerId&&this.finishPointerInteraction()},this.close=()=>{this.finishPointerInteraction(),this.onClose?.()}}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),this.ensureWorkspaceScope()}willUpdate(){this.ensureWorkspaceScope()}disconnectedCallback(){this.finishPointerInteraction(),this.statusRequest+=1,this.diffRequest+=1,window.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}render(){return g`
5913
5945
  <div class="git-update-manager-backdrop" role="dialog" aria-modal="true" aria-label="Git Update Manager">
5914
5946
  <section class=${this.bounds===void 0?`git-update-manager-frame`:`git-update-manager-frame git-update-manager-frame-positioned`} style=${this.frameStyle()}>
5915
5947
  <header class="git-update-manager-header">
@@ -5943,15 +5975,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5943
5975
  ></div>
5944
5976
  </section>
5945
5977
  </div>
5946
- `}ensureWorkspaceScope(){let e=qk(this.workspace,this.machineId);e!==this.workspaceScope&&(this.workspaceScope=e,this.statusRequest+=1,this.diffRequest+=1,this.status=void 0,this.selectedChange=void 0,this.selectedDiff=void 0,this.loadingStatus=!1,this.loadingDiff=!1,this.error=``,e!==void 0&&this.isConnected&&this.refresh())}renderChangeList(){if(this.loadingStatus)return g`<p class="git-update-manager-empty">Loading changes…</p>`;let e=this.status;if(e===void 0)return g`<p class="git-update-manager-empty">Refresh to load Git changes.</p>`;if(!e.isGitRepo)return g`<p class="git-update-manager-empty">This workspace is not a Git repository.</p>`;let t=Es(e.files);return t.staged.length===0&&t.unstaged.length===0?g`<p class="git-update-manager-empty">No Git changes.</p>`:g`
5978
+ `}ensureWorkspaceScope(){let e=Jk(this.workspace,this.machineId);e!==this.workspaceScope&&(this.workspaceScope=e,this.statusRequest+=1,this.diffRequest+=1,this.status=void 0,this.selectedChange=void 0,this.selectedDiff=void 0,this.loadingStatus=!1,this.loadingDiff=!1,this.error=``,e!==void 0&&this.isConnected&&this.refresh())}renderChangeList(){if(this.loadingStatus)return g`<p class="git-update-manager-empty">Loading changes…</p>`;let e=this.status;if(e===void 0)return g`<p class="git-update-manager-empty">Refresh to load Git changes.</p>`;if(!e.isGitRepo)return g`<p class="git-update-manager-empty">This workspace is not a Git repository.</p>`;let t=Es(e.files);return t.staged.length===0&&t.unstaged.length===0?g`<p class="git-update-manager-empty">No Git changes.</p>`:g`
5947
5979
  ${this.renderChangeGroup(`staged`,t.staged)}
5948
5980
  ${this.renderChangeGroup(`unstaged`,t.unstaged)}
5949
- `}renderChangeGroup(e,t){if(t.length===0)return null;let n=Kk(e);return g`
5981
+ `}renderChangeGroup(e,t){if(t.length===0)return null;let n=qk(e);return g`
5950
5982
  <section class="git-update-manager-change-group" aria-label=${`${n} changes`}>
5951
5983
  <h2>${n} (${String(t.length)})</h2>
5952
5984
  ${t.map(e=>this.renderChange(e))}
5953
5985
  </section>
5954
- `}renderChange(e){let t=this.selectedChange?.id===e.id,n=As(e),r=ks(e.state),i=Kk(e.scope);return g`
5986
+ `}renderChange(e){let t=this.selectedChange?.id===e.id,n=As(e),r=ks(e.state),i=qk(e.scope);return g`
5955
5987
  <button
5956
5988
  type="button"
5957
5989
  class=${`git-update-manager-entry ${t?`selected`:``}`}
@@ -5963,13 +5995,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5963
5995
  <span class="git-update-manager-path">${n}</span>
5964
5996
  <span class="git-update-manager-scope">${i}</span>
5965
5997
  </button>
5966
- `}renderDiffPreview(){let e=this.selectedChange;if(e===void 0)return g`<p class="git-update-manager-empty">Select a Git change to review.</p>`;if(this.error!==``)return g`<p class="git-update-manager-empty">Could not load ${As(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${As(e)}…</p>`;let t=this.selectedDiff;return Wk(),g`
5998
+ `}renderDiffPreview(){let e=this.selectedChange;if(e===void 0)return g`<p class="git-update-manager-empty">Select a Git change to review.</p>`;if(this.error!==``)return g`<p class="git-update-manager-empty">Could not load ${As(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${As(e)}…</p>`;let t=this.selectedDiff;return Gk(),g`
5967
5999
  <header class="git-update-manager-diff-header">
5968
6000
  <strong>${As(e)}</strong>
5969
- <small>${Kk(e.scope)} · ${ks(e.state)}${t.truncated?` · truncated`:``}</small>
6001
+ <small>${qk(e.scope)} · ${ks(e.state)}${t.truncated?` · truncated`:``}</small>
5970
6002
  </header>
5971
6003
  <unified-diff-viewer .diff=${t.diff}></unified-diff-viewer>
5972
- `}async loadDiff(e,t,n){let r=++this.diffRequest;this.loadingDiff=!0;try{let i=await this.api.gitDiff(t.projectId,t.id,{path:e.path,staged:e.scope===`staged`},n);if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=i,this.loadingDiff=!1,this.error=``}catch(i){if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=void 0,this.loadingDiff=!1,this.error=Jk(i)}}startPointerInteraction(e,t){if(t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.git-update-manager-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=$g(this.boundsFromFrame(r),this.viewport());n.setPointerCapture(t.pointerId),this.bounds=i,this.pointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}boundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}viewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}frameStyle(){let e=this.bounds;return e===void 0?``:`left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px;`}finishPointerInteraction(){let e=this.pointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.pointerInteraction=void 0}}isCurrentWorkspace(e,t){return this.workspace?.id===e.id&&this.workspace.projectId===e.projectId&&this.machineId===t}static{this.styles=h`
6004
+ `}async loadDiff(e,t,n){let r=++this.diffRequest;this.loadingDiff=!0;try{let i=await this.api.gitDiff(t.projectId,t.id,{path:e.path,staged:e.scope===`staged`},n);if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=i,this.loadingDiff=!1,this.error=``}catch(i){if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=void 0,this.loadingDiff=!1,this.error=Yk(i)}}startPointerInteraction(e,t){if(t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.git-update-manager-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=$g(this.boundsFromFrame(r),this.viewport());n.setPointerCapture(t.pointerId),this.bounds=i,this.pointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}boundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}viewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}frameStyle(){let e=this.bounds;return e===void 0?``:`left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px;`}finishPointerInteraction(){let e=this.pointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.pointerInteraction=void 0}}isCurrentWorkspace(e,t){return this.workspace?.id===e.id&&this.workspace.projectId===e.projectId&&this.machineId===t}static{this.styles=h`
5973
6005
  :host { position: fixed; inset: 0; z-index: 80; color: var(--pi-text); font: 14px system-ui, sans-serif; }
5974
6006
  .git-update-manager-backdrop { width: 100%; height: 100dvh; display: grid; place-items: center; padding: 16px; background: rgba(0, 0, 0, .48); }
5975
6007
  .git-update-manager-frame { position: relative; display: flex; flex-direction: column; width: min(calc(100vw - 32px), 1280px); height: min(calc(100vh - 32px), 880px); overflow: hidden; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 64px var(--pi-shadow-strong); }
@@ -6008,7 +6040,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6008
6040
  .git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
6009
6041
  .git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
6010
6042
  }
6011
- `}};B([x({attribute:!1})],Uk.prototype,`onClose`,void 0),B([x({attribute:!1})],Uk.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],Uk.prototype,`workspace`,void 0),B([x()],Uk.prototype,`machineId`,void 0),B([x({attribute:!1})],Uk.prototype,`api`,void 0),B([S()],Uk.prototype,`status`,void 0),B([S()],Uk.prototype,`selectedChange`,void 0),B([S()],Uk.prototype,`selectedDiff`,void 0),B([S()],Uk.prototype,`loadingStatus`,void 0),B([S()],Uk.prototype,`loadingDiff`,void 0),B([S()],Uk.prototype,`error`,void 0),B([S()],Uk.prototype,`bounds`,void 0),Uk=B([b(`git-update-manager-panel`)],Uk);function Wk(){Sm(()=>import(`./UnifiedDiffViewer-jpQy9-p7.js`),[],import.meta.url)}function Gk(e,t){let n=Es(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function Kk(e){return e===`staged`?`Staged`:`Unstaged`}function qk(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function Jk(e){return e instanceof Error?e.message:String(e)}var Yk=900*1e3,Xk=750,Zk=[1e3,3e3,8e3,15e3,3e4],Qk={capture:!0},$k=`auto:on`,eA=`auto:off`,tA=`theme:`,nA=ns(`core:workspace.files`),rA=ns(`core:workspace.git`),iA=ns(`core:workspace.terminal`),aA=`workspace-memory`,oA=`workspace.memory`,sA=`workspace-memory:workspace.memory`,cA=320,lA=2,uA=`(min-width: 1181px)`,$=class extends y{constructor(...e){super(...e),this.state=Wo(),this.sessionUnread=new fp({onChange:e=>{R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new zd(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Ku(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Iu,{notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.workspaces=new qd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Gd,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new Hs(()=>this.state,{workspaces:so.workspaces,applySnapshot:async e=>{await this.workspaces.reconcileProjectCatalog(e)},captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectActivityOwnership=new Xs(()=>this.state,e=>{this.setState(e)},{api:so,captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onProjectTopology:async e=>{let t=this.state.projects.find(t=>t.id===e.projectId&&t.path===e.projectPath);t!==void 0&&await this.workspaces.reconcileProjectCatalog({machineId:e.machineId,project:t,workspaces:e.workspaces,...e.topologyRequest===void 0?{}:{topologyRequest:e.topologyRequest}})},onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Xo(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new $o(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Rs(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Ps(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Qs(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new hs(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new xs(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new ws(()=>this.state,e=>{this.setState(e)}),this.keyboard=new wf,this.realtime=new fu,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new of,this.terminalSelection=new yf,this.appShell=new qh(this),this.browserResume=new Yh({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new dg(this),this.panelResize=new hg(this),this.navigationSections=new cg(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=dA(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=jp()??Dp,this.activeThemeId=Ep,this.isRefreshingApp=!1,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.sessionBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=o_(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.terminalTabHidden=MA(),this.infoTabHidden=FA(),this.railOrder=Lk()??[...jk],this.settingsSection=Ig(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=wo(void 0),this.sessionWarningVisibility=bp(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onTerminalModalViewportResize=()=>{this.terminalModalBounds!==void 0&&(this.terminalModalBounds=$g(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||(this.sessions.startSessionWithPrompt(e,t,n,r),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleOpenTerminalFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,Rk(e)},this.handleCloseTerminalModal=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalOpen=!1},this.toggleTerminalModalMaximized=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalMaximized=!this.terminalModalMaximized},this.handleTerminalModalMovePointerDown=e=>{this.startTerminalModalPointerInteraction(`move`,e)},this.handleTerminalModalResizePointerDown=e=>{this.startTerminalModalPointerInteraction(`resize`,e)},this.handleTerminalModalPointerMove=e=>{let t=this.terminalModalPointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY},r=this.terminalModalViewport();this.terminalModalBounds=t.operation===`move`?Zg(t.bounds,n,r):Qg(t.bounds,n,r)},this.handleTerminalModalPointerUp=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishTerminalModalPointerInteraction())},this.handleTerminalModalPointerCancel=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&this.finishTerminalModalPointerInteraction()},this.adjustTerminalFontSize=e=>{let t=i_(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=a_(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Tp(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=mA(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Sp(this.sessionWarningVisibility,e===void 0?void 0:Jo(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=pA(e,t);await this.updateComplete,!(!this.unreadConnected||mA(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);SA(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=p_(this.state.selectedProject?.name);this.windowTitleCleanup=m_(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=pA(e,t);return mA(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.historyWindow!==void 0||this.modelsConfigDialogOpen||this.skillsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.pluginsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.systemPromptDialogOpen&&this.state.selectedSession!==void 0||this.state.actionPaletteOpen||this.projectBrowserOpen||this.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen}connectedCallback(){super.connectedCallback(),this.synchronizeProjectCatalogPolling(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,Qk),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},Yk),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.finishTerminalModalPointerInteraction(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,Qk),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.projectCatalog.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.memory.dispose(),this.piWebUiStatusTimer!==void 0&&window.clearInterval(this.piWebUiStatusTimer),this.piWebUiStatusTimer=void 0,this.clearScheduledPiWebUiStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),this.disconnectWindowTitle(),super.disconnectedCallback()}setState(e){if(!xA(this.state,e))return;let t=this.state;this.state={...this.state,...e},mA(t)!==mA(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),_A(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),!this.shouldShowSessionStartScreen(t)&&this.shouldShowSessionStartScreen(this.state)&&this.state.selectedWorkspace!==void 0&&this.loadStarterSessionDefaults(this.state.selectedWorkspace),this.handleMachineChange(t,this.state),vA(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=jg();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=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,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()])}schedulePiWebUiStatusRefresh(e=Xk){this.clearScheduledPiWebUiStatusRefresh(),this.piWebUiStatusDeferredTimer=window.setTimeout(()=>{this.piWebUiStatusDeferredTimer=void 0,this.piWebUiStatusController.refresh()},e)}clearScheduledPiWebUiStatusRefresh(){this.piWebUiStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebUiStatusDeferredTimer),this.piWebUiStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>bA(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await qa.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=wo(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let 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(jg(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?TA():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),R(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?TA():{selectedFilePath:is(nA,`file`),selectedDiffPath:is(rA,`diff`),selectedTerminalId:is(iA,`terminal`)}}routeForSelectedMachine(e){let 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){Mg(e,{replace:!0}),as(nA,`file`,void 0,{replace:!0}),as(rA,`diff`,void 0,{replace:!0}),as(iA,`terminal`,void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.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=DA(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;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(n?.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>=Zk.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.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){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await AA(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),Mg({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(cf(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(cf(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Mg(lf(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){as(nA,`file`,e.selectedFilePath,{replace:!0}),as(rA,`diff`,e.selectedDiffPath,{replace:!0}),as(iA,`terminal`,e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??sf(e.id);if(await this.restoreRouteFor(lf(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);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=R(this.state)){let n=EA(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Ug(e,{api:{runTerminalCommand:(e,n)=>lo.runTerminalCommand(e,n,t),listCommandRuns:e=>lo.listCommandRuns(e,t),getCommandRun:e=>lo.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((R(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:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)){this.setState({error:`Machine not found for terminal command run`});return}this.openTerminal(n)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let 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){as(iA,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(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,Lg(e)}closeSettings(){this.settingsSection=void 0,Lg(void 0)}navigateSettings(e){this.settingsSection=e,Lg(e)}restoreSettingsRoute(){this.settingsSection=Ig()}handleWorkspaceChange(e,t){let n=gA(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&this.synchronizeMemoryPollingForSelectedWorkspace();return}this.starterSessionDefaults=void 0,this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let r=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));if(this.setState({activeTerminalCount:0,selectedTerminalId:r}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(r,{replace:!0})),t.selectedWorkspace===void 0){this.synchronizeMemoryPollingForSelectedWorkspace();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace()}async loadStarterSessionDefaults(e){let t=R(this.state);try{let n=await co.sessionDefaults(e.path,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.starterSessionDefaults=n}catch(n){R(this.state)===t&&this.state.selectedWorkspace?.id===e.id&&console.warn(`Failed to load Pi session defaults`,n)}}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:Gt(e,T.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e),this.projectCatalog.refresh()},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new fu;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>yA(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):wA(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let 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){let t=R(this.state);try{let n=await lo.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=CA(e),r=CA(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
6043
+ `}};B([x({attribute:!1})],Wk.prototype,`onClose`,void 0),B([x({attribute:!1})],Wk.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],Wk.prototype,`workspace`,void 0),B([x()],Wk.prototype,`machineId`,void 0),B([x({attribute:!1})],Wk.prototype,`api`,void 0),B([S()],Wk.prototype,`status`,void 0),B([S()],Wk.prototype,`selectedChange`,void 0),B([S()],Wk.prototype,`selectedDiff`,void 0),B([S()],Wk.prototype,`loadingStatus`,void 0),B([S()],Wk.prototype,`loadingDiff`,void 0),B([S()],Wk.prototype,`error`,void 0),B([S()],Wk.prototype,`bounds`,void 0),Wk=B([b(`git-update-manager-panel`)],Wk);function Gk(){Sm(()=>import(`./UnifiedDiffViewer-DpWiGlQo.js`),[],import.meta.url)}function Kk(e,t){let n=Es(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function qk(e){return e===`staged`?`Staged`:`Unstaged`}function Jk(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function Yk(e){return e instanceof Error?e.message:String(e)}var Xk=900*1e3,Zk=750,Qk=[1e3,3e3,8e3,15e3,3e4],$k={capture:!0},eA=`auto:on`,tA=`auto:off`,nA=`theme:`,rA=ns(`core:workspace.files`),iA=ns(`core:workspace.git`),aA=ns(`core:workspace.terminal`),oA=`workspace-memory`,sA=`workspace.memory`,cA=`workspace-memory:workspace.memory`,lA=320,uA=2,dA=`(min-width: 1181px)`,$=class extends y{constructor(...e){super(...e),this.state=Wo(),this.sessionUnread=new fp({onChange:e=>{R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new zd(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Ku(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Iu,{notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.workspaces=new qd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Gd,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new Hs(()=>this.state,{workspaces:so.workspaces,applySnapshot:async e=>{await this.workspaces.reconcileProjectCatalog(e)},captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectActivityOwnership=new Xs(()=>this.state,e=>{this.setState(e)},{api:so,captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onProjectTopology:async e=>{let t=this.state.projects.find(t=>t.id===e.projectId&&t.path===e.projectPath);t!==void 0&&await this.workspaces.reconcileProjectCatalog({machineId:e.machineId,project:t,workspaces:e.workspaces,...e.topologyRequest===void 0?{}:{topologyRequest:e.topologyRequest}})},onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Xo(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new $o(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Rs(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Ps(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Qs(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new hs(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new xs(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new ws(()=>this.state,e=>{this.setState(e)}),this.keyboard=new wf,this.realtime=new fu,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new of,this.terminalSelection=new yf,this.appShell=new qh(this),this.browserResume=new Yh({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new dg(this),this.panelResize=new hg(this),this.navigationSections=new cg(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=fA(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=jp()??Dp,this.activeThemeId=Ep,this.isRefreshingApp=!1,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.sessionBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=o_(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.terminalTabHidden=NA(),this.infoTabHidden=IA(),this.railOrder=Rk()??[...Mk],this.settingsSection=Ig(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=wo(void 0),this.sessionWarningVisibility=bp(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onTerminalModalViewportResize=()=>{this.terminalModalBounds!==void 0&&(this.terminalModalBounds=$g(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||(this.sessions.startSessionWithPrompt(e,t,n,r),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleOpenTerminalFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,zk(e)},this.handleCloseTerminalModal=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalOpen=!1},this.toggleTerminalModalMaximized=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalMaximized=!this.terminalModalMaximized},this.handleTerminalModalMovePointerDown=e=>{this.startTerminalModalPointerInteraction(`move`,e)},this.handleTerminalModalResizePointerDown=e=>{this.startTerminalModalPointerInteraction(`resize`,e)},this.handleTerminalModalPointerMove=e=>{let t=this.terminalModalPointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY},r=this.terminalModalViewport();this.terminalModalBounds=t.operation===`move`?Zg(t.bounds,n,r):Qg(t.bounds,n,r)},this.handleTerminalModalPointerUp=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishTerminalModalPointerInteraction())},this.handleTerminalModalPointerCancel=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&this.finishTerminalModalPointerInteraction()},this.adjustTerminalFontSize=e=>{let t=i_(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=a_(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Tp(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=hA(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Sp(this.sessionWarningVisibility,e===void 0?void 0:Jo(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=mA(e,t);await this.updateComplete,!(!this.unreadConnected||hA(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);CA(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=p_(this.state.selectedProject?.name);this.windowTitleCleanup=m_(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=mA(e,t);return hA(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.historyWindow!==void 0||this.modelsConfigDialogOpen||this.skillsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.pluginsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.systemPromptDialogOpen&&this.state.selectedSession!==void 0||this.state.actionPaletteOpen||this.projectBrowserOpen||this.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen}connectedCallback(){super.connectedCallback(),this.synchronizeProjectCatalogPolling(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,$k),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},Xk),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.finishTerminalModalPointerInteraction(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,$k),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.projectCatalog.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.memory.dispose(),this.piWebUiStatusTimer!==void 0&&window.clearInterval(this.piWebUiStatusTimer),this.piWebUiStatusTimer=void 0,this.clearScheduledPiWebUiStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),this.disconnectWindowTitle(),super.disconnectedCallback()}setState(e){if(!SA(this.state,e))return;let t=this.state;this.state={...this.state,...e},hA(t)!==hA(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),vA(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),!this.shouldShowSessionStartScreen(t)&&this.shouldShowSessionStartScreen(this.state)&&this.state.selectedWorkspace!==void 0&&this.loadStarterSessionDefaults(this.state.selectedWorkspace),this.handleMachineChange(t,this.state),yA(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=jg();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=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,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()])}schedulePiWebUiStatusRefresh(e=Zk){this.clearScheduledPiWebUiStatusRefresh(),this.piWebUiStatusDeferredTimer=window.setTimeout(()=>{this.piWebUiStatusDeferredTimer=void 0,this.piWebUiStatusController.refresh()},e)}clearScheduledPiWebUiStatusRefresh(){this.piWebUiStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebUiStatusDeferredTimer),this.piWebUiStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>xA(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await qa.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=wo(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let 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(jg(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?EA():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),R(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?EA():{selectedFilePath:is(rA,`file`),selectedDiffPath:is(iA,`diff`),selectedTerminalId:is(aA,`terminal`)}}routeForSelectedMachine(e){let 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){Mg(e,{replace:!0}),as(rA,`file`,void 0,{replace:!0}),as(iA,`diff`,void 0,{replace:!0}),as(aA,`terminal`,void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.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=OA(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;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(n?.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>=Qk.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.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){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await jA(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),Mg({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(cf(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(cf(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Mg(lf(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){as(rA,`file`,e.selectedFilePath,{replace:!0}),as(iA,`diff`,e.selectedDiffPath,{replace:!0}),as(aA,`terminal`,e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??sf(e.id);if(await this.restoreRouteFor(lf(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);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=R(this.state)){let n=DA(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Ug(e,{api:{runTerminalCommand:(e,n)=>lo.runTerminalCommand(e,n,t),listCommandRuns:e=>lo.listCommandRuns(e,t),getCommandRun:e=>lo.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((R(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:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)){this.setState({error:`Machine not found for terminal command run`});return}this.openTerminal(n)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let 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){as(aA,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(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,Lg(e)}closeSettings(){this.settingsSection=void 0,Lg(void 0)}navigateSettings(e){this.settingsSection=e,Lg(e)}restoreSettingsRoute(){this.settingsSection=Ig()}handleWorkspaceChange(e,t){let n=_A(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&this.synchronizeMemoryPollingForSelectedWorkspace();return}this.starterSessionDefaults=void 0,this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let r=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));if(this.setState({activeTerminalCount:0,selectedTerminalId:r}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(r,{replace:!0})),t.selectedWorkspace===void 0){this.synchronizeMemoryPollingForSelectedWorkspace();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace()}async loadStarterSessionDefaults(e){let t=R(this.state);try{let n=await co.sessionDefaults(e.path,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.starterSessionDefaults=n}catch(n){R(this.state)===t&&this.state.selectedWorkspace?.id===e.id&&console.warn(`Failed to load Pi session defaults`,n)}}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:Gt(e,T.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e),this.projectCatalog.refresh()},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new fu;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>bA(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):TA(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let 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){let t=R(this.state);try{let n=await lo.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=wA(e),r=wA(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
6012
6044
  <workspace-panel
6013
6045
  id="workspace-panel"
6014
6046
  .workspace=${e}
@@ -6055,7 +6087,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6055
6087
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
6056
6088
  .onReset=${()=>{this.resetResizablePanel(`workspace`)}}
6057
6089
  ></app-panel-edge-control>
6058
- `}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-lA-cA);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let 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)||window.matchMedia(uA).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||Gt(e,T.sessionsDeleteArchived)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsReload)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return Cu(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&Gt(t,T.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return ap(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[R(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=R(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await co.cleanupPreview(e,t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${OA(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Qf(t.previewRequest)!==Qf(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=R(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await co.cleanup(e,n);if(R(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){R(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${OA(e)}`})}}async runForceSessionCleanup(){let e=this.sessionCleanupDialog;if(!this.canCleanupSessions()){this.sessionCleanupDialog={...e??{},error:this.sessionCleanupUnavailableMessage(),runningForce:!1};return}let t=R(this.state);this.sessionCleanupDialog={...e??{},runningForce:!0,error:``};try{let e=await co.forceCleanup(t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,forceCleanupResult:e,runningForce:!1,error:``},await this.sessions.applySessionCleanupResult(e,t)}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,runningForce:!1,error:`Failed to force cleanup: ${OA(e)}`})}}renderNavigationPanel(){return g`
6090
+ `}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-uA-lA);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let 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)||window.matchMedia(dA).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||Gt(e,T.sessionsDeleteArchived)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsReload)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return Cu(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&Gt(t,T.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return ap(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[R(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=R(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await co.cleanupPreview(e,t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${kA(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Qf(t.previewRequest)!==Qf(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=R(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await co.cleanup(e,n);if(R(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){R(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${kA(e)}`})}}async runForceSessionCleanup(){let e=this.sessionCleanupDialog;if(!this.canCleanupSessions()){this.sessionCleanupDialog={...e??{},error:this.sessionCleanupUnavailableMessage(),runningForce:!1};return}let t=R(this.state);this.sessionCleanupDialog={...e??{},runningForce:!0,error:``};try{let e=await co.forceCleanup(t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,forceCleanupResult:e,runningForce:!1,error:``},await this.sessions.applySessionCleanupResult(e,t)}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,runningForce:!1,error:`Failed to force cleanup: ${kA(e)}`})}}renderNavigationPanel(){return g`
6059
6091
  <app-navigation-panel
6060
6092
  .machines=${this.state.machines}
6061
6093
  .selectedMachine=${this.state.selectedMachine}
@@ -6131,14 +6163,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6131
6163
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
6132
6164
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
6133
6165
  ></app-navigation-panel>
6134
- `}canOpenSessionHistory(){let e=this.state.selectedSession;return e!==void 0&&e.persisted!==!1&&e.path!==``}openSessionHistory(){let e=this.state.selectedSession;e===void 0||!this.canOpenSessionHistory()||(this.historyWindow={machineId:R(this.state),session:e})}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}cancelPendingNavigationSelection(){this.navigationSelectionSeq+=1}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async selectSessionFromNavigation(e){if(this.state.selectedWorkspace?.path===e.cwd){await this.sessions.selectSession(e);return}let t=this.state.workspaces.find(t=>t.path===e.cwd);if(t===void 0){this.setState({error:`The session's workspace is no longer available.`});return}await this.workspaces.selectWorkspace(t,{sessionId:e.id})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e===`chat`){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e===`machines`&&!yk(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 AA(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await AA(),this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=R(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
6166
+ `}canOpenSessionHistory(){let e=this.state.selectedSession;return e!==void 0&&e.persisted!==!1&&e.path!==``}openSessionHistory(){let e=this.state.selectedSession;e===void 0||!this.canOpenSessionHistory()||(this.historyWindow={machineId:R(this.state),session:e})}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}cancelPendingNavigationSelection(){this.navigationSelectionSeq+=1}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async selectSessionFromNavigation(e){if(this.state.selectedWorkspace?.path===e.cwd){await this.sessions.selectSession(e);return}let t=this.state.workspaces.find(t=>t.path===e.cwd);if(t===void 0){this.setState({error:`The session's workspace is no longer available.`});return}await this.workspaces.selectWorkspace(t,{sessionId:e.id})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e===`chat`){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e===`machines`&&!bk(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 jA(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await jA(),this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=R(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
6135
6167
  <session-tree-navigator
6136
6168
  .tree=${e.treeDialog}
6137
6169
  .onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
6138
6170
  .onAbort=${()=>this.sessions.abortTreeNavigation()}
6139
6171
  .onCancel=${()=>{this.closeSessionTreeNavigator()}}
6140
6172
  ></session-tree-navigator>
6141
- `}workspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e),n=this.plugins.getWorkspacePanels();return this.synchronizeMemoryPolling(n,t),n.filter(e=>e.visible?.(t)??!0)}synchronizeMemoryPollingForSelectedWorkspace(){let e=this.state.selectedWorkspace;if(e===void 0){this.memory.updatePolling(!1);return}let t=this.createWorkspacePanelContext(e);this.synchronizeMemoryPolling(this.plugins.getWorkspacePanels(),t)}synchronizeMemoryPolling(e,t){let n=e.some(e=>hA(e)&&(e.visible?.(t)??!0));this.memory.updatePolling(n)}visibleWorkspacePanels(){let e=this.hiddenWorkspacePanelTools();return this.workspacePanels().filter(t=>!e.includes(t.id))}hiddenWorkspacePanelTools(){let e=[];return this.terminalTabHidden&&e.push(`core:workspace.terminal`),this.infoTabHidden&&e.push(`core:workspace.info`),e}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:`Loading projects…`,body:`Looking for projects you have added to PI WEBUI.`}: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.isLoadingSessions?`Loading sessions…`:this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?`Add a project to start a session.`:`Select a project and workspace to start a session.`:`Select a workspace to start a session.`:`Select or start a session.`}shouldShowSessionStartScreen(e){return e.selectedWorkspace!==void 0&&e.selectedSession===void 0&&!e.isLoadingSessions&&e.sessions.every(e=>e.archived===!0)&&e.error===``}renderSessionStartScreen(e){let t=e.selectedWorkspace;if(t===void 0)return g``;let n=this.starterSessionDefaults,r=n!==void 0&&n.models.length>0,i=n!==void 0&&n.thinkingLevels.length>0;return g`
6173
+ `}workspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e),n=this.plugins.getWorkspacePanels();return this.synchronizeMemoryPolling(n,t),n.filter(e=>e.visible?.(t)??!0)}synchronizeMemoryPollingForSelectedWorkspace(){let e=this.state.selectedWorkspace;if(e===void 0){this.memory.updatePolling(!1);return}let t=this.createWorkspacePanelContext(e);this.synchronizeMemoryPolling(this.plugins.getWorkspacePanels(),t)}synchronizeMemoryPolling(e,t){let n=e.some(e=>gA(e)&&(e.visible?.(t)??!0));this.memory.updatePolling(n)}visibleWorkspacePanels(){let e=this.hiddenWorkspacePanelTools();return this.workspacePanels().filter(t=>!e.includes(t.id))}hiddenWorkspacePanelTools(){let e=[];return this.terminalTabHidden&&e.push(`core:workspace.terminal`),this.infoTabHidden&&e.push(`core:workspace.info`),e}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:`Loading projects…`,body:`Looking for projects you have added to PI WEBUI.`}: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.isLoadingSessions?`Loading sessions…`:this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?`Add a project to start a session.`:`Select a project and workspace to start a session.`:`Select a workspace to start a session.`:`Select or start a session.`}shouldShowSessionStartScreen(e){return e.selectedWorkspace!==void 0&&e.selectedSession===void 0&&!e.isLoadingSessions&&e.sessions.every(e=>e.archived===!0)&&e.error===``}renderSessionStartScreen(e){let t=e.selectedWorkspace;if(t===void 0)return g``;let n=this.starterSessionDefaults,r=n!==void 0&&n.models.length>0,i=n!==void 0&&n.thinkingLevels.length>0;return g`
6142
6174
  <section class="session-start-screen" aria-labelledby="session-start-heading">
6143
6175
  <div class="session-start-content">
6144
6176
  <p class="session-start-eyebrow">PI WEBUI · ${t.label}</p>
@@ -6150,7 +6182,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6150
6182
  <p class="session-start-hint">Describe a goal, paste a task, or attach a file to begin.</p>
6151
6183
  </div>
6152
6184
  </section>
6153
- `}mobilePanelBadge(e){let 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){let t=fA(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:n=>so.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await so.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await so.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await so.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=fA(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Fh({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:{open:t=>{this.openRuntimeTerminal(n,e,t)},runCommand:t=>a.runCommand({...t,workspace:e})},openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUiUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:To(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onRefreshMemory:()=>{this.memory.refresh()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return Bg(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.toggle-terminal-tab`,title:this.terminalTabHidden?`Show Terminal Tab`:`Hide Terminal Tab`,description:this.terminalTabHidden?`Show the terminal tab in the workspace panel`:`Hide the terminal tab from the workspace panel`,group:`View`,run:()=>{this.toggleTerminalTab()}},{id:`app.layout.toggle-info-tab`,title:this.infoTabHidden?`Show Info Tab`:`Hide Info Tab`,description:this.infoTabHidden?`Show the info tab in the workspace panel`:`Hide the info tab from the workspace panel`,group:`View`,run:()=>{this.toggleInfoTab()}},{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 WEBUI plugins`,()=>vh())}async loadPluginsForSelectedMachine(){let 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;let t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;let n=this.registerExternalPlugins(`PI WEBUI plugins from ${e.name}`,()=>vh(`api/machines/${encodeURIComponent(e.id)}/pi-webui-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.plugins.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,n),await n}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEBUI plugin ${t.id}`,e)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Ph({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.openProjectDialog()},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:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),checkForPiWebUiUpdates:()=>this.piWebUiStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Jd(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(qp(this.state,e))return;let t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?\n\nThis will run git worktree remove and delete:\n${e.path}\n\nThe Git branch will not be deleted.`))return;let n=R(this.state);try{let t=await so.deleteWorkspace(e.projectId,e.id,n);if(R(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(R(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){R(this.state)===n&&this.setState({error:`Failed to start workspace deletion: ${OA(e)}`})}}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(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(R(this.state)!==t)return;let n=Jp(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=R(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{let n=await this.terminalCommandRunsForOrigin(`core`,e).listCommandRuns(Wp(t.id));if(R(this.state)!==e)return;let r=Gp(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Yp(t)||await this.handleCompletedWorkspaceDeletionRun(t,e)}catch(e){console.warn(`Failed to refresh workspace deletion runs`,e)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){let e=Object.values(this.state.workspaceDeletionRuns).some(Yp);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=R(this.state)){if(R(this.state)!==t)return;let n=EA(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Jp(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),R(this.state)!==t)return;this.setState({workspaceDeletionRuns:kA(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace deletion failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}openProjectBrowser(e){this.projectBrowserRestoreFocus=e,this.projectBrowserOpen=!0}closeProjectBrowser(e={}){let t=e.restoreFocus===!0?this.projectBrowserRestoreFocus:void 0;this.projectBrowserRestoreFocus=void 0,this.projectBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectProjectFromBrowser(e){this.closeProjectBrowser(),this.selectNavigationItem(`projects`,`workspaces`,()=>this.workspaces.selectProject(e))}addProjectFromBrowser(){this.closeProjectBrowser(),this.openProjectDialog()}openSessionBrowser(e){this.state.selectedProject!==void 0&&(this.sessionBrowserRestoreFocus=e,this.sessionBrowserOpen=!0)}closeSessionBrowser(e={}){let t=e.restoreFocus===!0?this.sessionBrowserRestoreFocus:void 0;this.sessionBrowserRestoreFocus=void 0,this.sessionBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectSessionFromBrowser(e){this.closeSessionBrowser(),this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e))}openProjectDialog(){this.setState({projectDialogOpen:!0})}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebUiStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEBUI gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let 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=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id,r=[...e].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openStarterModelDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=e.model?.provider,n=e.model?.id,r=[...e.models].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Default Model`,source:`starter`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickStarterModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.updateStarterSessionDefaults({model:{provider:e.slice(0,t),modelId:e.slice(t+1)}})}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?eA:$k;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${tA}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${tA}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===$k||e===eA){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===$k},this.applyPreferredTheme(!0);return}if(!e.startsWith(tA))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,Np(t),e&&Mp(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Pp({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Ip(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){let n=[...e.id===t?[`selected`]:[],...e.id===this.activeThemeId&&e.id!==t?[`active`]:[]];return n.length===0?e.name:`${e.name} ✓ ${n.join(` · `)}`}themeOptionDescription(e){let 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(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=LA(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.sessions.setThinkingLevel(e)}openStarterThinkingDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=e.thinkingLevel;this.setState({thinkingDialog:{title:`Select Default Thinking Level`,source:`starter`,selectedValue:t,options:e.thinkingLevels.map(e=>{let n=LA(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickStarterThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.updateStarterSessionDefaults({thinkingLevel:e})}async updateStarterSessionDefaults(e){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state);try{let r=await co.updateSessionDefaults(t.path,e,n);if(R(this.state)!==n||this.state.selectedWorkspace?.id!==t.id)return;this.starterSessionDefaults=r}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.setState({error:String(e)})}}sendPrompt(e,t,n,r){!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,n,r)}applyGitUpdateManagerStatus(e,t,n){let r=this.state.selectedWorkspace;R(this.state)!==t||r?.id!==e.id||r.projectId!==e.projectId||this.setState({gitStatus:n,gitStale:!1})}startTerminalModalPointerInteraction(e,t){if(this.terminalModalMaximized||t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.terminal-modal-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=$g(this.terminalModalBoundsFromFrame(r),this.terminalModalViewport());n.setPointerCapture(t.pointerId),this.terminalModalBounds=i,this.terminalModalPointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}terminalModalBoundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}terminalModalViewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}terminalModalFrameStyle(){let e=this.terminalModalMaximized?void 0:this.terminalModalBounds,t=e===void 0?``:`; left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px`;return`--terminal-modal-opacity: ${String(this.terminalModalOpacity)}%${t};`}finishTerminalModalPointerInteraction(){let e=this.terminalModalPointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.terminalModalPointerInteraction=void 0}}persistTerminalModalPreferences(){s_({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,NA(this.terminalTabHidden)}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,IA(this.infoTabHidden)}renderChatView(e,t){return g`
6185
+ `}mobilePanelBadge(e){let 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){let t=pA(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:n=>so.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await so.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await so.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await so.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=pA(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Fh({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:{open:t=>{this.openRuntimeTerminal(n,e,t)},runCommand:t=>a.runCommand({...t,workspace:e})},openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUiUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:To(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onRefreshMemory:()=>{this.memory.refresh()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return Bg(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.toggle-terminal-tab`,title:this.terminalTabHidden?`Show Terminal Tab`:`Hide Terminal Tab`,description:this.terminalTabHidden?`Show the terminal tab in the workspace panel`:`Hide the terminal tab from the workspace panel`,group:`View`,run:()=>{this.toggleTerminalTab()}},{id:`app.layout.toggle-info-tab`,title:this.infoTabHidden?`Show Info Tab`:`Hide Info Tab`,description:this.infoTabHidden?`Show the info tab in the workspace panel`:`Hide the info tab from the workspace panel`,group:`View`,run:()=>{this.toggleInfoTab()}},{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 WEBUI plugins`,()=>vh())}async loadPluginsForSelectedMachine(){let 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;let t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;let n=this.registerExternalPlugins(`PI WEBUI plugins from ${e.name}`,()=>vh(`api/machines/${encodeURIComponent(e.id)}/pi-webui-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.plugins.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,n),await n}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEBUI plugin ${t.id}`,e)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Ph({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.openProjectDialog()},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:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),checkForPiWebUiUpdates:()=>this.piWebUiStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Jd(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(qp(this.state,e))return;let t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?\n\nThis will run git worktree remove and delete:\n${e.path}\n\nThe Git branch will not be deleted.`))return;let n=R(this.state);try{let t=await so.deleteWorkspace(e.projectId,e.id,n);if(R(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(R(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){R(this.state)===n&&this.setState({error:`Failed to start workspace deletion: ${kA(e)}`})}}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(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(R(this.state)!==t)return;let n=Jp(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=R(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{let n=await this.terminalCommandRunsForOrigin(`core`,e).listCommandRuns(Wp(t.id));if(R(this.state)!==e)return;let r=Gp(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Yp(t)||await this.handleCompletedWorkspaceDeletionRun(t,e)}catch(e){console.warn(`Failed to refresh workspace deletion runs`,e)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){let e=Object.values(this.state.workspaceDeletionRuns).some(Yp);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=R(this.state)){if(R(this.state)!==t)return;let n=DA(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Jp(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),R(this.state)!==t)return;this.setState({workspaceDeletionRuns:AA(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace deletion failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}openProjectBrowser(e){this.projectBrowserRestoreFocus=e,this.projectBrowserOpen=!0}closeProjectBrowser(e={}){let t=e.restoreFocus===!0?this.projectBrowserRestoreFocus:void 0;this.projectBrowserRestoreFocus=void 0,this.projectBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectProjectFromBrowser(e){this.closeProjectBrowser(),this.selectNavigationItem(`projects`,`workspaces`,()=>this.workspaces.selectProject(e))}addProjectFromBrowser(){this.closeProjectBrowser(),this.openProjectDialog()}openSessionBrowser(e){this.state.selectedProject!==void 0&&(this.sessionBrowserRestoreFocus=e,this.sessionBrowserOpen=!0)}closeSessionBrowser(e={}){let t=e.restoreFocus===!0?this.sessionBrowserRestoreFocus:void 0;this.sessionBrowserRestoreFocus=void 0,this.sessionBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectSessionFromBrowser(e){this.closeSessionBrowser(),this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e))}openProjectDialog(){this.setState({projectDialogOpen:!0})}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebUiStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEBUI gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let 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=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id,r=[...e].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openStarterModelDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=e.model?.provider,n=e.model?.id,r=[...e.models].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Default Model`,source:`starter`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickStarterModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.updateStarterSessionDefaults({model:{provider:e.slice(0,t),modelId:e.slice(t+1)}})}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?tA:eA;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${nA}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${nA}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===eA||e===tA){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===eA},this.applyPreferredTheme(!0);return}if(!e.startsWith(nA))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,Np(t),e&&Mp(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Pp({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Ip(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){let n=[...e.id===t?[`selected`]:[],...e.id===this.activeThemeId&&e.id!==t?[`active`]:[]];return n.length===0?e.name:`${e.name} ✓ ${n.join(` · `)}`}themeOptionDescription(e){let 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(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=RA(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.sessions.setThinkingLevel(e)}openStarterThinkingDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=e.thinkingLevel;this.setState({thinkingDialog:{title:`Select Default Thinking Level`,source:`starter`,selectedValue:t,options:e.thinkingLevels.map(e=>{let n=RA(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickStarterThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.updateStarterSessionDefaults({thinkingLevel:e})}async updateStarterSessionDefaults(e){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state);try{let r=await co.updateSessionDefaults(t.path,e,n);if(R(this.state)!==n||this.state.selectedWorkspace?.id!==t.id)return;this.starterSessionDefaults=r}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.setState({error:String(e)})}}sendPrompt(e,t,n,r){!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,n,r)}applyGitUpdateManagerStatus(e,t,n){let r=this.state.selectedWorkspace;R(this.state)!==t||r?.id!==e.id||r.projectId!==e.projectId||this.setState({gitStatus:n,gitStale:!1})}startTerminalModalPointerInteraction(e,t){if(this.terminalModalMaximized||t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.terminal-modal-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=$g(this.terminalModalBoundsFromFrame(r),this.terminalModalViewport());n.setPointerCapture(t.pointerId),this.terminalModalBounds=i,this.terminalModalPointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}terminalModalBoundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}terminalModalViewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}terminalModalFrameStyle(){let e=this.terminalModalMaximized?void 0:this.terminalModalBounds,t=e===void 0?``:`; left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px`;return`--terminal-modal-opacity: ${String(this.terminalModalOpacity)}%${t};`}finishTerminalModalPointerInteraction(){let e=this.terminalModalPointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.terminalModalPointerInteraction=void 0}}persistTerminalModalPreferences(){s_({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,PA(this.terminalTabHidden)}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,LA(this.infoTabHidden)}renderChatView(e,t){return g`
6154
6186
  <chat-view .sessionId=${t.id} .sessionInfo=${t} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isSendingPrompt=${e.sendingPrompts[t.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[t.id]??[]} .status=${e.status} .warningCount=${this.sessionWarningVisibility.warningCount} .warningsExpanded=${this.sessionWarningVisibility.warningCount>0&&!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .activity=${e.activity} .notificationInbox=${bd(e.selectedNotificationInbox)} .canClearServerQueue=${this.canClearServerQueue()} .onClearServerQueue=${this.handleClearServerQueue} .canMessageActions=${this.canMessageActions()&&t.archived!==!0} .onEditFromHere=${this.handleEditFromHere} .onForkFromHere=${this.handleForkFromHere} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
6155
6187
  `}renderContextBar(){return this.appShell.isMobileNavigationLayout?g`
6156
6188
  <app-context-bar
@@ -6318,4 +6350,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6318
6350
  ${this.terminalModalOpen?this.renderTerminalModal():null}
6319
6351
  ${this.settingsSection===void 0?null:g`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .onNavigate=${e=>{this.navigateSettings(e)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${e=>{this.applyClientConfig(e)}} .onRefreshMachineRuntime=${async e=>{await this.machines.refreshMachineRuntime(e)}}></settings-dialog>`}
6320
6352
  </div>
6321
- `}static{this.styles=um}};B([S()],$.prototype,`state`,void 0),B([C(`chat-view`)],$.prototype,`chatView`,void 0),B([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),B([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),B([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),B([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),B([S()],$.prototype,`unreadSessionIds`,void 0),B([S()],$.prototype,`activeThemeId`,void 0),B([S()],$.prototype,`isRefreshingApp`,void 0),B([S()],$.prototype,`sessionCleanupDialog`,void 0),B([S()],$.prototype,`historyWindow`,void 0),B([S()],$.prototype,`starterSessionDefaults`,void 0),B([S()],$.prototype,`modelsConfigDialogOpen`,void 0),B([S()],$.prototype,`projectBrowserOpen`,void 0),B([S()],$.prototype,`sessionBrowserOpen`,void 0),B([S()],$.prototype,`skillsConfigDialogOpen`,void 0),B([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),B([S()],$.prototype,`systemPromptDialogOpen`,void 0),B([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),B([S()],$.prototype,`terminalModalOpen`,void 0),B([S()],$.prototype,`terminalModalBounds`,void 0),B([S()],$.prototype,`terminalModalMaximized`,void 0),B([S()],$.prototype,`terminalModalFontSize`,void 0),B([S()],$.prototype,`terminalModalOpacity`,void 0),B([S()],$.prototype,`terminalTabHidden`,void 0),B([S()],$.prototype,`infoTabHidden`,void 0),B([S()],$.prototype,`railOrder`,void 0),B([S()],$.prototype,`settingsSection`,void 0),B([S()],$.prototype,`shortcutConfig`,void 0),B([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=B([b(`pi-webui-app`)],$);function dA(){let e=new jh;return e.register({id:`core`,plugin:ch}),e.register({id:`themes`,plugin:fh}),e}function fA(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:`local`,kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function pA(e,t){return JSON.stringify([e,t.id,t.cwd])}function mA(e){let t=e.selectedSession;return t===void 0?void 0:pA(R(e),t)}function hA(e){return e.id===sA||e.sourcePluginId===aA&&e.localId===oA}function gA(e,t){return R(e)!==R(t)||e.selectedProject?.id!==t.selectedProject?.id||e.selectedWorkspace?.id!==t.selectedWorkspace?.id||e.selectedWorkspace?.path!==t.selectedWorkspace?.path}function _A(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function vA(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function yA(e,t){return bA(e,t)}function bA(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function xA(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function SA(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function CA(e){return Go(e.status,e.activity)}function wA(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function TA(){return{}}function EA(e,t){return JSON.stringify([e,t])}function DA(e){return Zk[Math.min(e,Zk.length-1)]??3e4}function OA(e){return e instanceof Error?e.message:String(e)}function kA(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function AA(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}var jA=`pi-webui:terminal-tab-hidden`;function MA(){try{let e=typeof localStorage>`u`?void 0:localStorage;return e!==void 0&&e.getItem(jA)===`true`}catch{return!1}}function NA(e){try{let t=typeof localStorage>`u`?void 0:localStorage;if(t===void 0)return;e?t.setItem(jA,`true`):t.removeItem(jA)}catch{}}var PA=`pi-webui:info-tab-hidden`;function FA(){try{let e=typeof localStorage>`u`?void 0:localStorage;return e!==void 0&&e.getItem(PA)===`true`}catch{return!1}}function IA(e){try{let t=typeof localStorage>`u`?void 0:localStorage;if(t===void 0)return;e?t.setItem(PA,`true`):t.removeItem(PA)}catch{}}function LA(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)`;default:return}}export{y as a,b as i,C as n,g as o,x as r,h as s,B as t};
6353
+ `}static{this.styles=um}};B([S()],$.prototype,`state`,void 0),B([C(`chat-view`)],$.prototype,`chatView`,void 0),B([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),B([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),B([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),B([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),B([S()],$.prototype,`unreadSessionIds`,void 0),B([S()],$.prototype,`activeThemeId`,void 0),B([S()],$.prototype,`isRefreshingApp`,void 0),B([S()],$.prototype,`sessionCleanupDialog`,void 0),B([S()],$.prototype,`historyWindow`,void 0),B([S()],$.prototype,`starterSessionDefaults`,void 0),B([S()],$.prototype,`modelsConfigDialogOpen`,void 0),B([S()],$.prototype,`projectBrowserOpen`,void 0),B([S()],$.prototype,`sessionBrowserOpen`,void 0),B([S()],$.prototype,`skillsConfigDialogOpen`,void 0),B([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),B([S()],$.prototype,`systemPromptDialogOpen`,void 0),B([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),B([S()],$.prototype,`terminalModalOpen`,void 0),B([S()],$.prototype,`terminalModalBounds`,void 0),B([S()],$.prototype,`terminalModalMaximized`,void 0),B([S()],$.prototype,`terminalModalFontSize`,void 0),B([S()],$.prototype,`terminalModalOpacity`,void 0),B([S()],$.prototype,`terminalTabHidden`,void 0),B([S()],$.prototype,`infoTabHidden`,void 0),B([S()],$.prototype,`railOrder`,void 0),B([S()],$.prototype,`settingsSection`,void 0),B([S()],$.prototype,`shortcutConfig`,void 0),B([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=B([b(`pi-webui-app`)],$);function fA(){let e=new jh;return e.register({id:`core`,plugin:ch}),e.register({id:`themes`,plugin:fh}),e}function pA(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:`local`,kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function mA(e,t){return JSON.stringify([e,t.id,t.cwd])}function hA(e){let t=e.selectedSession;return t===void 0?void 0:mA(R(e),t)}function gA(e){return e.id===cA||e.sourcePluginId===oA&&e.localId===sA}function _A(e,t){return R(e)!==R(t)||e.selectedProject?.id!==t.selectedProject?.id||e.selectedWorkspace?.id!==t.selectedWorkspace?.id||e.selectedWorkspace?.path!==t.selectedWorkspace?.path}function vA(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function yA(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function bA(e,t){return xA(e,t)}function xA(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function SA(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function CA(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function wA(e){return Go(e.status,e.activity)}function TA(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function EA(){return{}}function DA(e,t){return JSON.stringify([e,t])}function OA(e){return Qk[Math.min(e,Qk.length-1)]??3e4}function kA(e){return e instanceof Error?e.message:String(e)}function AA(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function jA(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}var MA=`pi-webui:terminal-tab-hidden`;function NA(){try{let e=typeof localStorage>`u`?void 0:localStorage;return e!==void 0&&e.getItem(MA)===`true`}catch{return!1}}function PA(e){try{let t=typeof localStorage>`u`?void 0:localStorage;if(t===void 0)return;e?t.setItem(MA,`true`):t.removeItem(MA)}catch{}}var FA=`pi-webui:info-tab-hidden`;function IA(){try{let e=typeof localStorage>`u`?void 0:localStorage;return e!==void 0&&e.getItem(FA)===`true`}catch{return!1}}function LA(e){try{let t=typeof localStorage>`u`?void 0:localStorage;if(t===void 0)return;e?t.setItem(FA,`true`):t.removeItem(FA)}catch{}}function RA(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)`;default:return}}export{y as a,b as i,C as n,g as o,x as r,h as s,B as t};