@hyperdreamer/pi-webui 1.11.0-beta.2 → 1.11.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-BLl9w8U8.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-B645sjuo.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`,modelTierSettings:`settings.modelTiers`},Et=[`economy`,`fast`,`standard`,`advanced`,`capable`,`frontier`],Dt=1e3,Ot=32*1024,kt=8*1024,At=1e4;function jt(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function Mt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&jt(e)}var Nt=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),Pt=/^sha256:[0-9a-f]{64}$/u,Ft=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,It=new Set([`PI_WEBUI_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function Lt(e){if(!Ht(e)||Object.keys(e).some(e=>!Nt.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`||!Pt.test(n))&&!(typeof r!=`string`||!Rt(r))&&!(typeof i!=`string`||!zt(i))&&Vt(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEBUI_AGENT_SESSION_DIR`||a.some(e=>!It.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Rt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:zt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):Ft.test(e)}function zt(e){if(e===``||e!==e.trim()||Bt(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Bt(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Vt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Ht(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ut=Object.values(T),Wt=new Set(Ut);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.modelTierSettings,T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsMessageActions,T.sessionsSystemPrompt,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.promptAttachments,T.modelTierSettings,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.modelTierSettings;function Gt(e){return typeof e==`string`&&Wt.has(e)}function Kt(e,t){return e?.capabilities?.includes(t)===!0}function qt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Gt)}function Jt(e){return typeof e==`object`&&!!e}function E(e){if(!Jt(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 Yt(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function Xt(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Zt(e){if(!Jt(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:Qt(e.globalEntries),projectEntries:Qt(e.projectEntries),...typeof e.projectUnavailableMessage==`string`?{projectUnavailableMessage:e.projectUnavailableMessage}:{}}}function Qt(e){if(!Array.isArray(e))throw Error(`Invalid memory snapshot response`);return e.map(e=>{if(!Jt(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 $t(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=E(e);return{messages:Yt(t.messages),start:k(t,`start`),total:k(t,`total`)}}function en(e){let t=E(e);return j(tn)(t.machines)}function tn(e){let t=E(e),n=an(t,`kind`),r=O(t,`baseUrl`),i=on(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 nn(e){let t=E(e),n=on(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:$i(t.web)},...t.sessiond===void 0?{}:{sessiond:$i(t.sessiond)},...r===void 0?{}:{error:r}}}function rn(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:Zi(t.components)},...t.capabilities===void 0?{}:{capabilities:aa(t.capabilities)},...n===void 0?{}:{error:n}}}function an(e,t){let n=D(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function on(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 sn(e){let t=E(e);return{id:D(t,`id`),name:D(t,`name`),path:D(t,`path`),createdAt:D(t,`createdAt`)}}function cn(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`,ln(t.effectiveConfig))}}function ln(e){if(e!==void 0){if(!Jt(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...N(`uploads`,wi(e.uploads))}}}function un(e){let t=E(e),n=O(t,`name`),r=qi(t.persisted,`persisted`),i=O(t,`parentSessionPath`),a=O(t,`archivedAt`),o=qi(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 dn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function fn(e){if(e!==void 0)return{id:D(E(e),`id`)}}function pn(e){let t=E(e),n=fn(t.dismiss);return{severity:dn(t.severity),message:D(t,`message`),...N(`source`,O(t,`source`)),...N(`path`,O(t,`path`)),...n===void 0?{}:{dismiss:n}}}function mn(e){return e===void 0?{}:{warnings:j(pn)(e)}}function hn(e){let t=E(e);return{sessionId:D(t,`sessionId`),...N(`persisted`,qi(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(Xn)(t.queuedMessages),...N(`messageCount`,M(t,`messageCount`)),tokens:Zn(t.tokens),cost:k(t,`cost`),...Vr(t.generation),...$n(t.model),...Hr(t.contextUsage),...N(`thinkingLevel`,O(t,`thinkingLevel`)),...mn(t.warnings)}}function gn(e){let t=E(e);return{seq:k(t,`seq`),partial:t.partial??null}}function _n(e){let t=O(E(e),`systemPrompt`);return t===void 0?{}:{systemPrompt:t}}function vn(e){let t=E(e),n=Ln(t,`catalogRevision`),r=Pn(t.sessions,bn,Dt,`sessions`);if(xn(r),Sn(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:Cn(t,`catalogId`,512),catalogRevision:n,sessions:r}}function yn(e){let t=E(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=Cn(t,`sessionId`,512),r=Cn(t,`cwd`,Ot),i=wn(t,`catalogRevision`),a=t.unread===null?null:bn(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:Cn(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function bn(e){let t=E(e),n=Cn(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:Cn(t,`sessionId`,512),cwd:Cn(t,`cwd`,Ot),completionOrder:wn(t,`completionOrder`),completedAt:n}}function xn(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 Sn(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 Cn(e,t,n){let r=In(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function wn(e,t){let n=Ln(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function Tn(e){let t=E(e),n=Dn(t.summary),r=Pn(t.notifications,On,100,`notifications`);if(Rn(r),zn(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==Vn(r))throw Error(`Notification snapshot severity mismatch`);let i=kn(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:In(t,`daemonInstanceId`),catalogRevision:Ln(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function En(e){let t=E(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=Dn(t.summary),r=kn(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=An(t.delta);if(i.kind===`cleared`&&!Bn(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:In(t,`daemonInstanceId`),catalogRevision:Ln(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function Dn(e){let t=E(e),n=Ln(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Ln(t,`discardedCount`),i=Mn(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:In(t,`sessionId`),cwd:In(t,`cwd`),inboxRevision:Ln(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function On(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=Ln(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:In(t,`id`),message:n,truncated:A(t,`truncated`),severity:jn(t.severity),receivedAt:r,order:i}}function kn(e){let t=E(e);return{order:Ln(t,`order`),overflowWatermark:Ln(t,`overflowWatermark`)}}function An(e){let t=E(e);switch(t.kind){case`added`:{let e=O(t,`evictedNotificationId`);return{kind:`added`,notification:On(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=Pn(t.notificationIds,Fn,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:Nn(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function jn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function Mn(e){return e===void 0?void 0:jn(e)}function Nn(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 Pn(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 Fn(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function In(e,t){let n=D(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function Ln(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 Rn(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 zn(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 Bn(e){return e.retainedCount===0&&e.discardedCount===0}function Vn(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Hn(e){let t=E(e),n=t.skippedBusySessionIds===void 0?void 0:Xt(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:D(t,`generatedAt`),thresholds:qn(t.thresholds),projects:j(Jn)(t.projects),totals:Yn(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Un(e){let t=E(e);return{...Hn(t),archivedSessionIds:Xt(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:Xt(t.deletedSessionIds,`deletedSessionIds`)}}function Wn(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:Xt(t.archivedSessionIds,`archivedSessionIds`),failures:j(Kn)(t.failures),generatedAt:D(t,`generatedAt`)}}function Gn(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:Xt(t.deletedSessionIds,`deletedSessionIds`),failures:j(Kn)(t.failures),generatedAt:D(t,`generatedAt`)}}function Kn(e){let t=E(e);return{sessionId:D(t,`sessionId`),error:D(t,`error`)}}function qn(e){let t=E(e);return{...N(`archiveIdleDays`,M(t,`archiveIdleDays`)),...N(`deleteArchivedDays`,M(t,`deleteArchivedDays`))}}function Jn(e){let t=E(e);return{cwd:D(t,`cwd`),archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function Yn(e){let t=E(e);return{archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function Xn(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 Zn(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 Qn(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 $n(e){return e===void 0?{}:{model:Qn(e)}}function er(e){let t=E(e);return{models:j(Qn)(t.models)}}function tr(e){let t=E(e);return{...t.model===void 0?{}:{model:Qn(t.model)},thinkingLevel:D(t,`thinkingLevel`),models:j(Qn)(t.models),thinkingLevels:Xt(t.thinkingLevels,`thinkingLevels`)}}function nr(e){let t=ar(e,`models configuration`),n=t.providers;if(n===void 0)return{...t,providers:{}};let r=ar(n,`models configuration providers`),i={};for(let[e,t]of Object.entries(r))i[e]=rr(t);return{...t,providers:i}}function rr(e){let t=ar(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=or(t.headers,`models configuration provider headers`);o!==void 0&&(n.headers=sr(o,`models configuration provider headers`));let s=or(t.compat,`models configuration provider compatibility`);s!==void 0&&(n.compat={...s});let c=or(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(ir)}return n}function ir(e){let t=ar(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=Aa(t,`reasoning`);a!==void 0&&(n.reasoning=a);let o=or(t.thinkingLevelMap,`models configuration thinking level map`);o!==void 0&&(n.thinkingLevelMap=cr(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=or(t.cost,`models configuration model cost`);u!==void 0&&(n.cost=lr(u));let d=or(t.compat,`models configuration model compatibility`);return d!==void 0&&(n.compat={...d}),n}function ar(e,t){if(!Jt(e)||Array.isArray(e))throw Error(`Expected ${t} object`);return e}function or(e,t){if(e!==void 0)return ar(e,t)}function sr(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 cr(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 lr(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 ur(e){if(E(e).success!==!0)throw Error(`Expected successful models configuration save`);return{success:!0}}function dr(e){let t=E(e);return{models:j(fr)(t.models)}}function fr(e){let t=E(e),n=D(t,`id`),r=O(t,`name`);return r===void 0?{id:n}:{id:n,name:r}}function pr(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 mr(e){let t=E(e);return{skills:j(hr)(t.skills)}}function hr(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:gr(t.install)}}}function gr(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:_r(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 _r(e){if(e!==`global`&&e!==`project`)throw Error(`Expected skill install scope`);return e}function vr(e){if(E(e).success!==!0)throw Error(`Expected successful Skills mutation`);return{success:!0}}function yr(e){let t=E(e);return{results:j(br)(t.results)}}function br(e){let t=E(e);return{package:D(t,`package`),installs:D(t,`installs`),url:D(t,`url`)}}function xr(e){let t=E(e);return{updates:j(Sr)(t.updates)}}function Sr(e){let t=E(e),n=O(t,`currentVersion`),r=O(t,`latestVersion`),i=O(t,`message`);return{package:D(t,`package`),scope:_r(t.scope),state:Cr(t.state),...n===void 0?{}:{currentVersion:n},...r===void 0?{}:{latestVersion:r},...i===void 0?{}:{message:i}}}function Cr(e){if(e!==`up-to-date`&&e!==`update-available`&&e!==`unsupported`&&e!==`error`)throw Error(`Expected skill update state`);return e}function wr(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:hr(t.skill)},...n===void 0?{}:{output:n}}}function Tr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Er(e){let t=E(e);return{levels:j(Tr)(t.levels)}}function Dr(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Or(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 kr(e){let t=E(e),n=t.source===void 0?void 0:Or(t.source);return{configured:A(t,`configured`),...N(`source`,n),...N(`label`,O(t,`label`))}}function Ar(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:Dr(t.authType),status:kr(t.status),...n===void 0?{}:{loginFlow:n}}}function jr(e){let t=E(e);return{providers:j(Ar)(t.providers)}}function Mr(e){let t=E(e);return{flowId:D(t,`flowId`),providerId:D(t,`providerId`),providerName:D(t,`providerName`),status:Nr(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`,Pr(t.auth)),...N(`prompt`,Ir(t.prompt)),...N(`select`,Rr(t.select)),...N(`info`,zr(t.info))}}function Nr(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function Pr(e){if(e===void 0)return;let t=E(e);return{url:D(t,`url`),...N(`instructions`,O(t,`instructions`)),...N(`deviceCode`,Fr(t.deviceCode))}}function Fr(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 Ir(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`:Lr(t.promptType);return{requestId:D(t,`requestId`),message:D(t,`message`),kind:n,promptType:r,...N(`placeholder`,O(t,`placeholder`)),...N(`allowEmpty`,Aa(t,`allowEmpty`))}}function Lr(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function Rr(e){if(e===void 0)return;let t=E(e);return{requestId:D(t,`requestId`),message:D(t,`message`),options:j(_a)(t.options)}}function zr(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(Br)(t.links))}})(e)}function Br(e){let t=E(e);return{url:D(t,`url`),...N(`label`,O(t,`label`))}}function Vr(e){if(e===void 0)return{};let t=E(e);return{generation:{outputTokens:k(t,`outputTokens`),...N(`tokensPerSecond`,M(t,`tokensPerSecond`)),...N(`estimated`,Aa(t,`estimated`))}}}function Hr(e){if(e===void 0)return{};let t=E(e);return{contextUsage:{tokens:ja(t,`tokens`),contextWindow:k(t,`contextWindow`),percent:ja(t,`percent`)}}}function Ur(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 Wr(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 Gr(e){let t=E(e);return{path:D(t,`path`),entries:j(Kr)(t.entries),scannedAt:D(t,`scannedAt`),truncated:A(t,`truncated`)}}function Kr(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 qr(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`,Zr(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 Jr(e){let t=E(e);return{path:D(t,`path`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),created:A(t,`created`)}}function Yr(e){let t=E(e);return{path:D(t,`path`),existed:A(t,`existed`)}}function Xr(e){let t=E(e);return{fromPath:D(t,`fromPath`),toPath:D(t,`toPath`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`)}}function Zr(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function Qr(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($r)(t.files)}}function $r(e){let t=E(e);return{path:D(t,`path`),...N(`oldPath`,O(t,`oldPath`)),index:ei(t.index),workingTree:ei(t.workingTree)}}function ei(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 ti(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 ni(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 ri(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:ii(t.status),...N(`exitCode`,M(t,`exitCode`)),createdAt:D(t,`createdAt`),...N(`startedAt`,O(t,`startedAt`)),...N(`completedAt`,O(t,`completedAt`)),metadata:ai(t.metadata,`metadata`)}}function ii(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function ai(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 oi(e){let t=E(e);return{cwd:D(t,`cwd`),hasSessionActivity:A(t,`hasSessionActivity`),hasTerminalActivity:A(t,`hasTerminalActivity`),updatedAt:D(t,`updatedAt`)}}function si(e){let t=E(e);return{workspaces:j(oi)(t.workspaces),generatedAt:D(t,`generatedAt`)}}function ci(e){let t=E(e);if(t.contractVersion!==1)throw Error(`Invalid model-tier settings contract version`);let n=t.ladder===void 0?void 0:li(t.ladder),r=O(t,`configError`);return{contractVersion:1,...N(`ladder`,n),models:j(fi)(t.models),rows:pi(t.rows),valid:A(t,`valid`),...N(`configError`,r)}}function li(e){let t=gi(e,`ladder`);return{economy:ui(t.economy,`ladder.economy`),fast:ui(t.fast,`ladder.fast`),standard:ui(t.standard,`ladder.standard`),advanced:ui(t.advanced,`ladder.advanced`),capable:ui(t.capable,`ladder.capable`),frontier:ui(t.frontier,`ladder.frontier`)}}function ui(e,t){let n=_i(e,t),r=Object.keys(n).find(e=>e!==`model`&&e!==`thinkingLevel`);if(r!==void 0)throw Error(`Invalid model-tier entry field: ${t}.${r}`);return{model:di(n.model,`${t}.model`),thinkingLevel:In(n,`thinkingLevel`)}}function di(e,t){let n=_i(e,t),r=Object.keys(n).find(e=>e!==`provider`&&e!==`id`);if(r!==void 0)throw Error(`Invalid model reference field: ${t}.${r}`);return{provider:In(n,`provider`),id:In(n,`id`)}}function fi(e){let t=_i(e,`models`);return{model:di(t.model,`models.model`),...N(`name`,O(t,`name`)),thinkingLevels:Xt(t.thinkingLevels,`models.thinkingLevels`)}}function pi(e){let t=gi(e,`rows`);return{economy:mi(t.economy,`rows.economy`),fast:mi(t.fast,`rows.fast`),standard:mi(t.standard,`rows.standard`),advanced:mi(t.advanced,`rows.advanced`),capable:mi(t.capable,`rows.capable`),frontier:mi(t.frontier,`rows.frontier`)}}function mi(e,t){let n=_i(e,t),r=Object.keys(n).find(e=>e!==`valid`&&e!==`reason`);if(r!==void 0)throw Error(`Invalid model-tier row field: ${t}.${r}`);return{valid:A(n,`valid`),...N(`reason`,O(n,`reason`))}}function hi(e){return Et.some(t=>t===e)}function gi(e,t){let n=_i(e,t),r=Object.keys(n).find(e=>!hi(e));if(r!==void 0)throw Error(`Invalid model-tier ${t} field: unknown tier ${r}`);let i=Et.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid model-tier ${t} field: missing tier ${i}`);return n}function _i(e,t){if(!Jt(e)||Array.isArray(e))throw Error(`Expected object field: ${t}`);return e}function vi(e){let t=E(e);return{path:D(t,`path`),exists:A(t,`exists`),config:yi(t.config),effectiveConfig:yi(t.effectiveConfig),envOverrides:ki(t.envOverrides)}}function yi(e){let t=E(e);return{...N(`host`,O(t,`host`)),...N(`port`,M(t,`port`)),...N(`allowedHosts`,xi(t.allowedHosts)),...N(`shortcuts`,Di(t.shortcuts)),...N(`plugins`,Oi(t.plugins)),...N(`pathAccess`,Si(t.pathAccess)),...N(`uploads`,wi(t.uploads)),...N(`maxUploadBytes`,M(t,`maxUploadBytes`)),...N(`agent`,bi(t.agent)),...N(`spawnSessions`,Aa(t,`spawnSessions`)),...N(`subsessions`,Aa(t,`subsessions`))}}function bi(e){if(e!==void 0){if(!Jt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI agent field`);return{...N(`command`,O(e,`command`)),...N(`dir`,O(e,`dir`))}}}function xi(e){if(e!==void 0){if(e===!0)return!0;if(Ti(e))return e;throw Error(`Invalid PI WEBUI allowedHosts field`)}}function Si(e){if(e===void 0)return;if(!Jt(e))throw Error(`Invalid PI WEBUI pathAccess field`);let t=e.allowedPaths;return{...N(`allowedPaths`,Ci(t,`pathAccess.allowedPaths`))}}function Ci(e,t){if(e!==void 0){if(Ei(e))return e;throw Error(`Invalid PI WEBUI ${t} field`)}}function wi(e){if(e!==void 0){if(!Jt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI uploads field`);return{...N(`defaultFolder`,O(e,`defaultFolder`))}}}function Ti(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Ei(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Di(e){if(e!==void 0){if(!Jt(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 Oi(e){if(e!==void 0){if(!Jt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!Jt(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&&(!Jt(r)||Array.isArray(r)))throw Error(`Invalid PI WEBUI plugin settings field`);return[e,t]}))}}function ki(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:Aa(t,`agentCommand`)??!1,agentDir:Aa(t,`agentDir`)??!1,...Ai(t),agentSessionDir:Aa(t,`agentSessionDir`)??!1}}function Ai(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 ji(e){let t=E(e);return{packages:j(Ni)(t.packages)}}function Mi(e){let t=E(e),n=O(t,`source`),r=t.scope===void 0?void 0:Pi(t.scope),i=qi(t.removed,`removed`);return{action:Fi(t.action),...N(`source`,n),...N(`scope`,r),...N(`removed`,i),packages:j(Ni)(t.packages)}}function Ni(e){let t=E(e);return{source:D(t,`source`),scope:Pi(t.scope),filtered:A(t,`filtered`),...N(`installedPath`,O(t,`installedPath`))}}function Pi(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function Fi(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Ii(e){let t=E(e);return{packages:j(Li)(t.packages),totals:Bi(t.totals),diagnostics:j(Ui)(t.diagnostics)}}function Li(e){let t=E(e);return{source:D(t,`source`),scope:Ri(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:Bi(t.counts),resources:j(Vi)(t.resources),status:zi(t.status)}}function Ri(e){if(e!==`global`&&e!==`project`)throw Error(`Invalid Pi package plugin scope`);return e}function zi(e){if(e!==`loaded`&&e!==`installed`&&e!==`missing`&&e!==`disabled`)throw Error(`Invalid Pi package plugin status`);return e}function Bi(e){let t=E(e);return{extensions:k(t,`extensions`),skills:k(t,`skills`),prompts:k(t,`prompts`),themes:k(t,`themes`)}}function Vi(e){let t=E(e);return{kind:Hi(t.kind),name:D(t,`name`),path:D(t,`path`),relativePath:D(t,`relativePath`)}}function Hi(e){if(e!==`extension`&&e!==`skill`&&e!==`prompt`&&e!==`theme`)throw Error(`Invalid Pi package plugin resource kind`);return e}function Ui(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 Wi(e){let t=E(e);return{plugins:j(Gi)(t.plugins)}}function Gi(e){let t=E(e);return{id:D(t,`id`),module:D(t,`module`),source:D(t,`source`),scope:Ki(t.scope),machineSpecific:qi(t.machineSpecific,`machineSpecific`)??!1,enabled:A(t,`enabled`)}}function Ki(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEBUI plugin scope`);return e}function qi(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function Ji(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Xi(t.components),release:ta(t.release),commands:na(t.commands),messages:j(ra)(t.messages)}}function Yi(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Zi(t.components),capabilities:aa(t.capabilities)}}function Xi(e){let t=E(e);return{web:$i(t.web),sessiond:$i(t.sessiond)}}function Zi(e){let t=E(e);return{web:Qi(t.web),sessiond:Qi(t.sessiond)}}function Qi(e){let t=E(e),n=ia(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:Lt(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:aa(t.capabilities),...N(`activeAgentProfile`,i),...N(`error`,O(t,`error`))}}function $i(e){let t=E(e);return{component:ia(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`,ea(t.installation)),...N(`error`,O(t,`error`))}}function ea(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 ta(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 na(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 ra(e){let t=E(e);return{id:D(t,`id`),severity:oa(t.severity),title:D(t,`title`),body:D(t,`body`),...N(`command`,O(t,`command`))}}function ia(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEBUI service component`);return e}function aa(e){let t=qt(e);if(t===void 0)throw Error(`Invalid PI WEBUI capabilities`);return t}function oa(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEBUI status severity`);return e}function sa(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(_a)(t.options)};if(n===`tree`)return{type:n,tree:ca(t.tree)};if(n===`done`)return{type:n,...N(`message`,O(t,`message`)),...va(t.session),...N(`promptDraft`,O(t,`promptDraft`))};throw Error(`Invalid command result type`)}function ca(e){let t=E(e),n=j(la)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=ma(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:ga(t.activePathIds,`activePathIds`)}}function la(e){let t=E(e);return{id:ha(t,`id`),parentId:ma(t,`parentId`),kind:ua(t.kind),summary:D(t,`summary`),...N(`timestamp`,O(t,`timestamp`)),...N(`label`,O(t,`label`))}}function ua(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 da(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){pa(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 pa(t,`aborted`,`session tree navigation result`),{cancelled:n,...N(`editorText`,O(t,`editorText`))}}function fa(e){let t=E(e);return A(t,`cancelled`)?(pa(t,`session`,`session fork cancellation result`),{cancelled:!0}):{cancelled:!1,session:un(t.session)}}function pa(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function ma(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 ha(e,t){let n=D(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function ga(e,t){let n=Xt(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function _a(e){let t=E(e);return{value:D(t,`value`),label:D(t,`label`),...N(`description`,O(t,`description`))}}function va(e){return e===void 0?{}:{session:un(e)}}function ya(e){if(E(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function ba(e){let t=E(e);return j(xa)(t.attachments)}function xa(e){let t=E(e);return{path:D(t,`path`),mimeType:D(t,`mimeType`),size:k(t,`size`)}}function Sa(e){if(E(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function Ca(e){if(E(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function wa(e){if(E(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function Ta(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:Xt(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 Ea(e){if(E(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function Da(e){if(E(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function Oa(e){if(E(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function ka(e){if(E(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function Aa(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 ja(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 Ma(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:Fa(r)}}function Na(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:Pa(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 Pa(e){let t={hostname:D(e,`hostname`),localIpv4Addresses:Xt(e.localIpv4Addresses,`localIpv4Addresses`),...Fa(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 Fa(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 Ia(e){return typeof e==`string`?e:e.id}function La(e){return typeof e==`string`?void 0:e.cwd}function Ra(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 za(e,t,n=`local`){let r=new URLSearchParams,i=La(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(Ia(e))}/messages${a===``?``:`?${a}`}`}function Ba(e,t=`local`){let n=new URLSearchParams,r=La(e);r!==void 0&&r!==``&&n.set(`cwd`,r);let i=n.toString();return`api/machines/${encodeURIComponent(t)}/sessions/${encodeURIComponent(Ia(e))}/export${i===``?``:`?${i}`}`}function Va(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 Ha(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 Ua(e){return typeof e==`string`?e:e.id}function Wa(e){return typeof e==`string`?void 0:e.cwd}function Ga(e,t=`local`){return`${P(t)}/sessions/${encodeURIComponent(Ua(e))}`}function F(e,t,n=`local`){return`${Ga(e,n)}/${t}`}function Ka(e,t,n=`local`){return`${F(e,t,n)}${Ja(e)}`}function qa(e,t=`local`){return`${Ga(e,t)}${Ja(e)}`}function Ja(e){let t=Wa(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function I(e,t={}){let n=Wa(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Ya(e){return JSON.stringify({sessions:e.map(Xa)})}function Xa(e){let t=Ua(e),n=Wa(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Za(e){return e===`local`?`api/pi-webui/status`:`${P(e)}/pi-webui/status`}var Qa={piWebUiStatus:(e=`local`)=>w(Za(e),Ji),checkForUpdates:(e=`local`)=>w(`${Za(e)}?refresh=1`,Ji,{cache:`no-store`}),piWebUiRuntime:()=>w(`api/pi-webui/runtime`,Yi),systemInfo:(e=`local`)=>w(`${P(e)}/pi-webui/system-info`,Na),systemMetrics:(e=`local`)=>w(`${P(e)}/pi-webui/system-metrics`,Ma,{cache:`no-store`})},$a={machines:()=>w(`api/machines`,en),addMachine:e=>w(`api/machines`,tn,{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`,nn),runtime:(e,t=!1)=>w(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,rn,t?{cache:`no-store`}:{})};function eo(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${P(t)}/agent-memory/snapshot?${n.toString()}`}var to={snapshot:(e,t=`local`)=>w(eo(e,t),Zt,{cache:`no-store`})};function no(e){return e===void 0?`api/config`:`${P(e)}/config`}function ro(e){return e===void 0?`api/plugins`:`${P(e)}/plugins`}var io={config:e=>w(no(e),vi),saveConfig:(e,t)=>w(no(t),vi,{method:`PUT`,body:JSON.stringify({config:e})})},ao={plugins:e=>w(ro(e),Wi)};function oo(e=`local`){return`${P(e)}/models-config`}var so={config:(e=`local`)=>w(oo(e),nr),save:(e,t=`local`)=>w(oo(t),ur,{method:`PUT`,body:JSON.stringify(e)}),test:(e,t=`local`)=>w(`${oo(t)}/test`,pr,{method:`POST`,body:JSON.stringify(e)}),discover:(e,t=`local`)=>w(`${oo(t)}/discover`,dr,{method:`POST`,body:JSON.stringify(e)})};function co(e=`local`){return`${P(e)}/model-tiers`}var lo={settings:(e=`local`)=>w(co(e),ci),save:(e,t=`local`)=>w(co(t),ci,{method:`PUT`,body:JSON.stringify({ladder:e})})};function uo(e=`local`){return`${P(e)}/skills`}function fo(e,t=`local`){return`${uo(t)}?${new URLSearchParams({cwd:e}).toString()}`}var po={list:(e,t=`local`)=>w(fo(e,t),mr),toggle:(e,t=`local`)=>w(uo(t),vr,{method:`PATCH`,body:JSON.stringify(e)}),search:(e,t=`local`)=>w(`${uo(t)}/search`,yr,{method:`POST`,body:JSON.stringify(e)}),install:(e,t=`local`)=>w(`${uo(t)}/install`,vr,{method:`POST`,body:JSON.stringify(e)}),check:(e,t=`local`)=>w(`${uo(t)}/check`,xr,{method:`POST`,body:JSON.stringify(e)}),update:(e,t=`local`)=>w(`${uo(t)}/update`,wr,{method:`POST`,body:JSON.stringify(e)})};function mo(e=``,t){let n=t===void 0?`api/pi-packages`:`${P(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var ho={packages:e=>w(mo(``,e),ji),install:(e,t)=>{let n={source:e};return w(mo(`install`,t),Mi,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return w(mo(`remove`,n),Mi,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return w(mo(`update`,t),Mi,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}};function go(e=`local`){return`${P(e)}/package-plugins`}function _o(e,t=`local`){return`${go(t)}?${new URLSearchParams({cwd:e}).toString()}`}var vo={list:(e,t=`local`)=>w(_o(e,t),Ii),mutate:(e,t=`local`)=>w(go(t),Ii,{method:`POST`,body:JSON.stringify(e)})},yo={workspaceActivity:(e=`local`)=>w(`${P(e)}/activity`,si)},bo={projects:(e=`local`)=>w(`${P(e)}/projects`,j(sn)),addProject:(e,t,n,r=`local`)=>w(`${P(r)}/projects`,sn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>w(`${P(t)}/projects/${encodeURIComponent(e)}`,Sa,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>w(`${P(t)}/project-directories?q=${encodeURIComponent(e)}`,j(Wr))},xo={workspaces:(e,t=`local`)=>w(`${P(t)}/projects/${encodeURIComponent(e)}/workspaces`,j(cn)),deleteWorkspace:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ri,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,Gr),workspaceFile:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,qr),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()}`,Jr,{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()}`,Yr,{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()}`,Xr,{method:`POST`})}},So={sessions:(e,t=`local`)=>w(`${P(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(un)),unreadCatalog:(e=`local`)=>w(`${P(e)}/sessions/unread`,vn,{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),vn,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>w(Ka(e,`notifications`,t),Tn),dismissNotification:(e,t,n,r=`local`)=>w(F(e,`notifications/dismiss`,r),Tn,{method:`POST`,body:I(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>w(F(e,`notifications/dismiss-all`,r),Tn,{method:`POST`,body:I(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`)=>w(`${P(t)}/sessions`,un,{method:`POST`,body:JSON.stringify({cwd:e})}),sessionDefaults:(e,t=`local`)=>w(`${P(t)}/session-defaults?cwd=${encodeURIComponent(e)}`,tr),updateSessionDefaults:(e,t,n=`local`)=>w(`${P(n)}/session-defaults`,tr,{method:`PUT`,body:JSON.stringify({cwd:e,...t})}),cleanupPreview:(e,t=`local`)=>w(`${P(t)}/sessions/cleanup/preview`,Hn,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>w(`${P(t)}/sessions/cleanup`,Un,{method:`POST`,body:JSON.stringify(e)}),forceCleanup:(e=`local`)=>w(`${P(e)}/sessions/cleanup/force`,Un,{method:`POST`}),archiveMany:(e,t=`local`)=>w(`${P(t)}/sessions/bulk/archive`,Wn,{method:`POST`,body:Ya(e)}),deleteArchivedMany:(e,t=`local`)=>w(`${P(t)}/sessions/bulk/delete-archived`,Gn,{method:`POST`,body:Ya(e)}),messages:(e,t,n=`local`)=>w(za(e,t,n),$t),status:(e,t=`local`)=>w(Ka(e,`status`,t),hn),systemPrompt:(e,t=`local`)=>w(Ka(e,`system-prompt`,t),_n),streamSnapshot:(e,t=`local`)=>w(Ka(e,`stream-snapshot`,t),gn),clearQueue:(e,t=`local`)=>w(F(e,`queue/clear`,t),hn,{method:`POST`,body:I(e)}),dismissWarning:(e,t,n=`local`)=>w(F(e,`warnings/dismiss`,n),hn,{method:`POST`,body:I(e,{dismissId:t})}),models:(e,t=`local`)=>w(Ka(e,`models`,t),er),setModel:(e,t,n,r=`local`)=>w(F(e,`model`,r),hn,{method:`POST`,body:I(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>w(F(e,`model/cycle`,n),hn,{method:`POST`,body:I(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>w(Ka(e,`thinking-levels`,t),Er),setThinkingLevel:(e,t,n=`local`)=>w(F(e,`thinking-level`,n),hn,{method:`POST`,body:I(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>w(F(e,`thinking-level/cycle`,t),hn,{method:`POST`,body:I(e)}),commands:(e,t=`local`)=>w(Ka(e,`commands`,t),j(Ur)),prompt:(e,t,n,r=`local`,i)=>w(F(e,`prompt`,r),ya,{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),ba,{method:`POST`,body:I(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>w(F(e,`shell`,n),ya,{method:`POST`,body:I(e,{text:t})}),runCommand:(e,t,n=`local`)=>w(F(e,`commands/run`,n),sa,{method:`POST`,body:I(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>w(F(e,`commands/respond`,r),sa,{method:`POST`,body:I(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>w(F(e,`tree/navigate`,n),da,{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),da,{method:`POST`,body:I(e,{entryId:t})}),forkFromHere:(e,t,n=`local`)=>w(F(e,`messages/fork`,n),fa,{method:`POST`,body:I(e,{entryId:t})}),abort:(e,t=`local`)=>w(F(e,`abort`,t),Ca,{method:`POST`,body:I(e)}),stop:(e,t=`local`)=>w(F(e,`stop`,t),wa,{method:`POST`,body:I(e)}),archive:(e,t=`local`)=>w(F(e,`archive`,t),Ta,{method:`POST`,body:I(e)}),archiveWithDescendants:(e,t=`local`)=>w(F(e,`archive-tree`,t),Ta,{method:`POST`,body:I(e)}),restore:(e,t=`local`)=>w(F(e,`restore`,t),Ea,{method:`POST`,body:I(e)}),deleteArchived:(e,t=`local`)=>w(qa(e,t),Da,{method:`DELETE`}),detachParent:(e,t=`local`)=>w(F(e,`detach-parent`,t),Oa,{method:`POST`,body:I(e)}),reloadSession:(e,t=`local`)=>w(F(e,`reload`,t),ka,{method:`POST`,body:I(e)}),pin:(e,t=`local`)=>w(F(e,`pin`,t),un,{method:`POST`,body:I(e)}),unpin:(e,t=`local`)=>w(F(e,`unpin`,t),un,{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}`}`,jr)},saveApiKey:(e,t,n=`local`)=>w(`${P(n)}/auth/api-key`,ya,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>w(`${P(t)}/auth/api-key/interactive`,Mr,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>w(`${P(t)}/auth/logout`,ya,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>w(`${P(t)}/auth/oauth`,Mr,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>w(`${P(t)}/auth/oauth/${encodeURIComponent(e)}`,Mr),respondOAuthFlow:(e,t,n,r=`local`)=>w(`${P(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,Mr,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>w(`${P(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Mr,{method:`POST`})},Co={terminals:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(ni)),startTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ni,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Sa,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,Sa,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,ni,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ri,{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${To(e)}`,j(ri)),getCommandRun:(e,t=`local`)=>wo(e,t),cancelCommandRun:(e,t=`local`)=>w(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ri,{method:`POST`})};async function wo(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(Eo(e)??n.statusText)}return ri(await n.json())}}function To(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 Eo(e){if(!Do(e))return;let t=e.error;return typeof t==`string`?t:void 0}function Do(e){return typeof e==`object`&&!!e}var Oo={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(Wr)):(r.set(`cwd`,e),w(`${P(n.machineId)}/files?${r.toString()}`,j(Wr)))}},ko={gitStatus:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Qr),gitDiff:(e,t,n,r=`local`)=>w(Ra(r,e,t,n),ti)},L={...Qa,...$a,...to,...lo,...io,...ao,...ho,...vo,...yo,...bo,...xo,...So,...Co,...Oo,...ko};function Ao(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(`${No(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function jo(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(`${No(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function Mo(e=`local`){return new WebSocket(xt(`${No(e)}/events`))}function No(e){return`api/machines/${encodeURIComponent(e)}`}var Po=`.pi-webui/uploads`,Fo=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},Io=class extends Error{constructor(e,t){super(qo(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function Lo(e){return e?.uploads?.defaultFolder??`.pi-webui/uploads`}function Ro(e,t){return e?.uploads?.defaultFolder??t}function zo(e,t){let n=Xo(e,`upload destination`,{allowEmpty:!0}),r=Xo(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function Bo(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`,Va(e,t,n.path,Uo(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Wo(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(Jr(Qo(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error($o(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new Fo(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function Vo(e,t,n,r={}){let i=r.destinationFolder??`.pi-webui/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:zo(i,e.name),loaded:0,total:e.size,percent:Ko(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(Go(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 Fo;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=Bo(e,t,{path:p.path,file:f},{...Ho(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(Yo(e,c))throw e;let t=Jo(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 Io(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function Ho(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 Uo(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Wo(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:Ko(e.loaded,n),lengthComputable:e.lengthComputable}}function Go(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:Ko(i,r),done:n}}function Ko(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function qo(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function Jo(e){return e instanceof Error?e.message:String(e)}function Yo(e,t){return t.requested||e instanceof Fo}function Xo(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Zo(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 Zo(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Qo(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function $o(e){let t=es(e);return ts(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function es(e){try{return Qo(e)}catch{return}}function ts(e){return typeof e==`object`&&!!e}function ns(){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 rs(){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 is(e,t){return t?.phase===`active`||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function as(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function os(e,t){return`${e}:${t}`}function ss(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var cs=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}},ls=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new cs,this.api=n.api??yo,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,us(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=ds(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 us(e){let t={};for(let n of e.workspaces)as(n)&&(t[n.cwd]=n);return t}function ds(e,t){let n={...e};return as(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var fs=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=ms(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||ps(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||ps(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`?ps(n.flow):void 0,a=ps(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=ps(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||ps(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||ps(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 ps(e){return e.prompt?.requestId??e.select?.requestId}function ms(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 hs(e){return e.replaceAll(`:`,`.`)}function gs(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 _s(e,t){let n=gs(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function vs(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));ys(i,r)}function ys(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 bs(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:zo(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:Es(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:Es(0,n),status:`uploading`,startedAt:e.startedAt}}function xs(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 Ss(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=Ts(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function Cs(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,...Ts(r),status:`error`,error:t,completedAt:n}}function ws(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,...Ts(r),status:`cancelled`,error:n,completedAt:t}}function Ts(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Es(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var Ds=hs(`core:workspace.files`),Os=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??Vo,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:Ms(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`}),vs(Ds,`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(ks(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),vs(Ds,`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=bs({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(ws(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:Ms(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(xs(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(Ss(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 Io)||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(As(t)){let e=ws(n,this.now());return this.setUploadBatch(e),e}let r=js(t),i=Cs(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 ks(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function As(e){return e instanceof Fo}function js(e){return e instanceof Error?e.message:String(e)}function Ms(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var Ns=hs(`core:workspace.git`),Ps=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}),vs(Ns,`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`}),vs(Ns,`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}},Fs=3e4,Is={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},Ls=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??to.snapshot,this.timer=n.timer??Is,this.pollIntervalMs=n.pollIntervalMs??Fs}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=Rs(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 Rs(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalEntries:e.globalEntries,projectEntries:e.projectEntries,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}function zs(e){let t=[],n=[];for(let r of e)Gs(r.index)&&t.push(Ws(r,`staged`,r.index)),Ks(r.workingTree)&&n.push(Ws(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function Bs(e){let t=zs(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function Vs(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 Hs(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 Us(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function Ws(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function Gs(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function Ks(e){return e!==`unmodified`&&e!==`ignored`}var qs=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:Ys(this.getState().machineActivities,r),machineRuntimes:Ys(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,...ns()}),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:Js(this.getState().machineStatuses,e.id),machineRuntimes:Js(this.getState().machineRuntimes,e.id),machineActivities:Js(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 Js(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Ys(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Xs=`~/workspace`,Zs=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(Xs,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)})}}},Qs=5e3,$s=`reconcile selected project catalog`,ec={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},tc=class{constructor(e,t){this.getState=e,this.generation=0,this.nextRequestId=0,this.observing=!1,this.listWorkspaces=t.workspaces??xo.workspaces,this.applySnapshot=t.applySnapshot,this.timer=t.timer??ec,this.pollIntervalMs=t.pollIntervalMs??Qs,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($s,e)}catch{}}};function nc(e,t){return t[e.path]}function rc(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function ic(e,t,n){return sc(cc(e,t,n))}function ac(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function oc(e){return sc(Object.values(e??{}))}function sc(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function cc(e,t,n){return Object.values(n).filter(n=>ac(e,t,n.cwd))}var lc=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??xo,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])=>!uc(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&&!uc(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(as).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 uc(e,t,n){return e.some(e=>ac(e,t[e.id]??[],n))}var dc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??Qa,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}),fc(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 fc(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 pc=`pi-webui:cached-new-sessions:v1`,mc=`browserCachedNew`,hc=`local`;function gc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function _c(e,t=hc,n=gc()){if(e.messageCount!==0||e.archived===!0)return;let r=Cc(n).filter(n=>n.id!==e.id||n.machineId!==t);wc([vc(e,t),...r],n)}function vc(e,t=hc){return{...e,browserCachedNew:!0,machineId:t}}function yc(e,t=hc,n=gc()){wc(Cc(n).filter(n=>n.id!==e||n.machineId!==t),n)}function bc(e,t,n=hc,r=gc()){let i=new Set(t.map(e=>e.id)),a=Cc(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&wc(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function xc(e){return e!==void 0&&Ec(e)&&e.browserCachedNew===!0}function Sc(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:hc},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Cc(e=gc()){try{let t=e?.getItem(pc);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Tc(e)):[]}catch{return[]}}function wc(e,t=gc()){try{e.length===0?t?.removeItem(pc):t?.setItem(pc,JSON.stringify(e))}catch{}}function Tc(e){if(!Dc(e))return[];let t=Oc(e,`id`),n=Oc(e,`path`),r=Oc(e,`cwd`),i=Oc(e,`created`),a=Oc(e,`modified`),o=Oc(e,`firstMessage`),s=Ac(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=kc(e,`name`),l=kc(e,`parentSessionPath`),u=kc(e,`machineId`)??hc;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 Ec(e){return mc in e}function Dc(e){return typeof e==`object`&&!!e}function Oc(e,t){let n=e[t];return typeof n==`string`?n:void 0}function kc(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function Ac(e,t){let n=e[t];return typeof n==`number`?n:void 0}function jc(e){return Xc(e.flatMap(Ic)).filter(e=>e.parts.length>0)}function Mc(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function Nc(e,t){let n=Hc(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=al(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 Pc(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,Mc(t,n)]}function Fc(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 Ic(e){if(Rc(e))return[e];if(z(e,`role`)===`bashExecution`)return[Nc(Gc(e),e)];let t=Kc(z(e,`role`)),n=qc(il(e,`content`),e),r=t===`user`?zc(n):void 0;if(r!==void 0)return r.map(t=>Nc(t,e));let i=Vc(e);if(t===`tool`)return[Nc({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?[Nc({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=Lc(e);return c===void 0?s:[...s,Nc(c,e)]}function Lc(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return Mc(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function Rc(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(il(e,`parts`))}function zc(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=Bc(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 Bc(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 Vc(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function Hc(e){let t=Uc(il(e,`timestamp`)),n=Wc(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function Uc(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 Wc(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 Gc(e){let t=z(e,`command`)??``,n=al(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=il(e,`output`);r!=null&&n.push(``,sl(r));let i=il(e,`exitCode`);i!=null&&n.push(``,`exit ${sl(i)}`),al(e,`cancelled`)===!0&&n.push(``,`cancelled`),al(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 Kc(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function qc(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=il(e,`arguments`),r=z(e,`id`),i=t===`read`?Yc(z(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:tl(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 el(e)}).map(e=>e.type===`text`&&z(t,`role`)===`toolResult`?Jc(e.text,t):e):el(e)}function Jc(e,t){let n=z(t,`toolCallId`),r=il(t,`content`),i=il(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:al(t,`isError`)===!0}}function Yc(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 Xc(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=Zc(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&&Qc(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function Zc(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 Qc(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=$c(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 $c(e){let t=il(e,`preview`);if(!rl(t))return;let n=z(t,`diff`),r=z(t,`error`),i=ol(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 el(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:tl(e)}]:[{type:`text`,text:sl(e)}]}function tl(e){if(!rl(e))return sl(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}: ${nl(t)}`).join(` · `)}function nl(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 rl(e){return typeof e==`object`&&!!e}function il(e,t){return rl(e)?e[t]:void 0}function z(e,t){let n=il(e,t);return typeof n==`string`?n:void 0}function al(e,t){let n=il(e,t);return typeof n==`boolean`?n:void 0}function ol(e,t){let n=il(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function sl(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var cl=`pi-webui:prompt-draft:`;function ll(e){return`${cl}${e}`}function ul(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function dl(e,t=ul()){try{return t?.getItem(ll(e))??``}catch{return``}}function fl(e,t,n=ul()){try{t?n?.setItem(ll(e),t):n?.removeItem(ll(e))}catch{}}function pl(e,t=ul()){try{t?.removeItem(ll(e))}catch{}}function ml(e,t,n=ul()){let r=dl(e,n);r!==``&&(fl(t,r,n),pl(e,n))}function hl(e,t){return Mc(`bash`,`${t===!0?`excluded from context
@@ -1107,7 +1107,7 @@ This will delete every archived session on this machine regardless of age or cle
1107
1107
  .review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1108
1108
  .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; }
1109
1109
  footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
1110
- `]}};B([x({attribute:!1})],Zm.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],Zm.prototype,`uploadInput`,void 0),B([S()],Zm.prototype,`pendingUpload`,void 0),B([S()],Zm.prototype,`destinationFolder`,void 0),B([S()],Zm.prototype,`overwrite`,void 0),B([S()],Zm.prototype,`createDirs`,void 0),B([S()],Zm.prototype,`formError`,void 0),B([S()],Zm.prototype,`dragActive`,void 0),Zm=B([b(`workspace-files-panel`)],Zm);function Qm(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 $m(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{zo(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function eh(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function th(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} · ${mh(t.size)}`}function nh(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function rh(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function ih(e){return e==null?[]:Array.from(e)}function ah(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function oh(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function sh(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 ch(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return fh(e.percent)}}function lh(e){return e.status===`uploading`?e.percent:1}function uh(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return fh(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function dh(e){return e.error===void 0?e.response===void 0?`${e.path} · ${mh(e.loaded)} / ${mh(e.total)}`:`Wrote ${e.response.path}`:e.error}function fh(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function ph(){Xm(()=>import(`./CodeViewer-BLl9w8U8.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function mh(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`${hh(t)} KB`;let n=t/1024;return n<1024?`${hh(n)} MB`:`${hh(n/1024)} GB`}function hh(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var gh=2e3,_h=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 Qa.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)},gh))}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 Qa.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">
1110
+ `]}};B([x({attribute:!1})],Zm.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],Zm.prototype,`uploadInput`,void 0),B([S()],Zm.prototype,`pendingUpload`,void 0),B([S()],Zm.prototype,`destinationFolder`,void 0),B([S()],Zm.prototype,`overwrite`,void 0),B([S()],Zm.prototype,`createDirs`,void 0),B([S()],Zm.prototype,`formError`,void 0),B([S()],Zm.prototype,`dragActive`,void 0),Zm=B([b(`workspace-files-panel`)],Zm);function Qm(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 $m(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{zo(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function eh(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function th(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} · ${mh(t.size)}`}function nh(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function rh(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function ih(e){return e==null?[]:Array.from(e)}function ah(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function oh(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function sh(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 ch(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return fh(e.percent)}}function lh(e){return e.status===`uploading`?e.percent:1}function uh(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return fh(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function dh(e){return e.error===void 0?e.response===void 0?`${e.path} · ${mh(e.loaded)} / ${mh(e.total)}`:`Wrote ${e.response.path}`:e.error}function fh(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function ph(){Xm(()=>import(`./CodeViewer-B645sjuo.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function mh(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`${hh(t)} KB`;let n=t/1024;return n<1024?`${hh(n)} MB`:`${hh(n/1024)} GB`}function hh(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var gh=2e3,_h=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 Qa.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)},gh))}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 Qa.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">
1111
1111
  <p class="error-text">Failed to load system information: ${this.error}</p>
1112
1112
  <button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
1113
1113
  </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">
@@ -1361,7 +1361,7 @@ This will delete every archived session on this machine regardless of age or cle
1361
1361
  <div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
1362
1362
  <unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
1363
1363
  </section>
1364
- `}function Ah(){Xm(()=>import(`./UnifiedDiffViewer-DmskjbU5.js`),[],import.meta.url)}function jh(){Xm(()=>Promise.resolve().then(()=>Fk),void 0,import.meta.url)}function Mh(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function Nh(e){let t=Ph(e);return g`
1364
+ `}function Ah(){Xm(()=>import(`./UnifiedDiffViewer-DVWEwLh_.js`),[],import.meta.url)}function jh(){Xm(()=>Promise.resolve().then(()=>Ik),void 0,import.meta.url)}function Mh(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function Nh(e){let t=Ph(e);return g`
1365
1365
  <p class="summary">
1366
1366
  <span class="summary-branch">${t.branch}</span>
1367
1367
  ${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
@@ -2352,7 +2352,7 @@ This will delete every archived session on this machine regardless of age or cle
2352
2352
  .custom-focus, .validation-error { margin-inline-start: 0; }
2353
2353
  footer { flex-wrap: wrap; }
2354
2354
  }
2355
- `}};B([x({attribute:!1})],Yy.prototype,`tree`,void 0),B([x({attribute:!1})],Yy.prototype,`onNavigate`,void 0),B([x({attribute:!1})],Yy.prototype,`onAbort`,void 0),B([x({attribute:!1})],Yy.prototype,`onCancel`,void 0),B([S()],Yy.prototype,`selectedId`,void 0),B([S()],Yy.prototype,`foldedIds`,void 0),B([S()],Yy.prototype,`step`,void 0),B([S()],Yy.prototype,`summaryMode`,void 0),B([S()],Yy.prototype,`customInstructions`,void 0),B([S()],Yy.prototype,`busy`,void 0),B([S()],Yy.prototype,`aborting`,void 0),B([S()],Yy.prototype,`error`,void 0),B([S()],Yy.prototype,`statusMessage`,void 0),Yy=B([b(`session-tree-navigator`)],Yy);function Xy(e){return Math.min(Math.max(0,e),Jy)}function Zy(e){return e===`user`||e===`custom-message`}function Qy(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 $y(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function eb(e){return e instanceof Error?e.message:String(e)}var tb=`pi-webui:chat-groups:`,nb={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(ib(e));return t===null||t===``?void 0:ab(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(ib(e),JSON.stringify(t))}catch{}}},rb=class{constructor(e=nb){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&&sb(i,this.openGroupKeys)&&sb(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 ib(e){return`${tb}${e}`}function ab(e){if(Array.isArray(e))return{open:ob(e),closedDefaultOpen:[]};if(cb(e))return{open:Array.isArray(e.open)?ob(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?ob(e.closedDefaultOpen):[]}}function ob(e){return e.filter(e=>typeof e==`string`)}function sb(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function cb(e){return typeof e==`object`&&!!e}function lb(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=>pb(e,t)),s=e.parts.filter(t=>!pb(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(db(t)){let e=fb(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 ub(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 db(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function fb(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function pb(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 mb(e,t=hb()){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 hb(){let e=e=>vb(e),t=_b();return t===void 0?{isSecureContext:gb(),fallbackWriteText:e}:{isSecureContext:gb(),writeText:t,fallbackWriteText:e}}function gb(){return typeof window<`u`&&window.isSecureContext}function _b(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function vb(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:yb(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(),bb(n,r),xb(t)}}function yb(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function bb(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function xb(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function Sb(e,t){let n=wb(Db(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function Cb(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Tb(r,t.markerOffset);return}e.scrollTop=Eb(e.scrollHeight,t.distanceFromBottom)}function wb(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 Tb(e,t){return e-t}function Eb(e,t){return Math.max(0,e-t)}function Db(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 Ob=600,kb=1;function Ab(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:jb(e)||Mb(e)}function jb(e){return e.scrollTop<(e.topThreshold??Math.max(Ob,e.clientHeight))}function Mb(e){return e.scrollHeight<=e.clientHeight+kb}var Nb=`pi-webui:chat-scroll:`,Pb=180,Fb=48,Ib=2,Lb={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)}},Rb={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},zb=class{constructor(e=Lb,t=Rb){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=Pb){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=Ib){if(e===``||t===void 0||!Hb(t))return`skipped`;try{if(Wb(t,r))return this.storage.setItem(Bb(e),JSON.stringify({mode:`bottom`})),`saved`;let i=Kb(t,n);if(i===void 0)return`skipped`;let a=Gb(t,i);return this.storage.setItem(Bb(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||!Hb(t))return{status:`skipped`};let i=Jb(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(Bb(e));if(t===null||t===``)return;let n=JSON.parse(t);return Vb(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!Hb(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function Bb(e){return`${Nb}${e}`}function Vb(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 Hb(e){return e.clientHeight>0&&e.scrollHeight>0}function Ub(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Wb(e,t=Fb){return Ub(e)<t}function Gb(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:Yb(t)??``,offset:t.getBoundingClientRect().top-n}}function Kb(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(Yb(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 qb(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function Jb(e,t){return e.find(e=>Yb(e)===t)}function Yb(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}function Xb(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?Zb(r/i):0,viewportRatio:Zb(n/t),visible:!0}}function Zb(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Qb(e,t){return Zb(e*(1-t))}function $b(e,t,n,r){return r<=0?0:Zb((e-t+n)/r)}var ex=22,tx=2;function nx(e,t){if(e.length===0)return[];let n=Number.isFinite(t)?Math.max(0,t):0,r=Math.max(0,n-ex),i=e.map((e,t)=>({index:t,desiredTop:Zb(e.topRatio)*n-ex/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*ex+(i.length-1)*tx>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 rx(e){if(typeof e!=`object`||!e||!(`ratio`in e))return;let t=e.ratio;if(!(typeof t!=`number`||!Number.isFinite(t)))return Zb(t)}function ix(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 ax(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function ox(e){return!Number.isFinite(e)||e===0?`$0.0000`:`$${e.toFixed(4)}`}function sx(e){return Number.isFinite(e)?Math.round(e).toLocaleString():`0`}function cx(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 lx(e){let t=[],n=e.tokens;t.push(`Input: ${sx(n.input)}`),t.push(`Output: ${sx(n.output)}`),t.push(`Cache read: ${sx(n.cacheRead)}`),t.push(`Cache write: ${sx(n.cacheWrite)}`),t.push(`Total: ${sx(n.total)}`),e.cost>0&&t.push(`Cost: ${ox(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 ${sx(r.contextWindow)} tokens`)}return t.join(` | `)}function ux(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 dx(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:sx(e.messageCount)}):(i.push({label:`User`,value:sx(n.user)}),i.push({label:`Assistant`,value:sx(n.assistant)}),i.push({label:`Tool calls`,value:sx(n.toolCalls)}),i.push({label:`Tool results`,value:sx(n.toolResults)}),i.push({label:`Total`,value:sx(n.total)}));let a=e.tokens,o=[{label:`Input`,value:sx(a.input)},{label:`Output`,value:sx(a.output)}];a.cacheRead>0&&o.push({label:`Cache read`,value:sx(a.cacheRead)}),a.cacheWrite>0&&o.push({label:`Cache write`,value:sx(a.cacheWrite)}),o.push({label:`Total`,value:sx(a.total)}),e.cost>0&&o.push({label:`Cost`,value:ox(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} / ${cx(s.contextWindow)}`})}return{sessionRows:r,messageRows:i,tokenRows:o}}var fx=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=Zb((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=Zb((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=Zb(this._viewportTopRatio()+n);this._dispatchScroll(r)}}_viewportTopRatio(){return Qb(this.scrollRatio,this.viewportRatio)}_dispatchScroll(e){let t=Zb(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`
2355
+ `}};B([x({attribute:!1})],Yy.prototype,`tree`,void 0),B([x({attribute:!1})],Yy.prototype,`onNavigate`,void 0),B([x({attribute:!1})],Yy.prototype,`onAbort`,void 0),B([x({attribute:!1})],Yy.prototype,`onCancel`,void 0),B([S()],Yy.prototype,`selectedId`,void 0),B([S()],Yy.prototype,`foldedIds`,void 0),B([S()],Yy.prototype,`step`,void 0),B([S()],Yy.prototype,`summaryMode`,void 0),B([S()],Yy.prototype,`customInstructions`,void 0),B([S()],Yy.prototype,`busy`,void 0),B([S()],Yy.prototype,`aborting`,void 0),B([S()],Yy.prototype,`error`,void 0),B([S()],Yy.prototype,`statusMessage`,void 0),Yy=B([b(`session-tree-navigator`)],Yy);function Xy(e){return Math.min(Math.max(0,e),Jy)}function Zy(e){return e===`user`||e===`custom-message`}function Qy(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 $y(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function eb(e){return e instanceof Error?e.message:String(e)}var tb=`pi-webui:chat-groups:`,nb={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(ib(e));return t===null||t===``?void 0:ab(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(ib(e),JSON.stringify(t))}catch{}}},rb=class{constructor(e=nb){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&&sb(i,this.openGroupKeys)&&sb(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 ib(e){return`${tb}${e}`}function ab(e){if(Array.isArray(e))return{open:ob(e),closedDefaultOpen:[]};if(cb(e))return{open:Array.isArray(e.open)?ob(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?ob(e.closedDefaultOpen):[]}}function ob(e){return e.filter(e=>typeof e==`string`)}function sb(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function cb(e){return typeof e==`object`&&!!e}function lb(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=>pb(e,t)),s=e.parts.filter(t=>!pb(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(db(t)){let e=fb(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 ub(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 db(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function fb(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function pb(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 mb(e,t=hb()){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 hb(){let e=e=>vb(e),t=_b();return t===void 0?{isSecureContext:gb(),fallbackWriteText:e}:{isSecureContext:gb(),writeText:t,fallbackWriteText:e}}function gb(){return typeof window<`u`&&window.isSecureContext}function _b(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function vb(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:yb(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(),bb(n,r),xb(t)}}function yb(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function bb(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function xb(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function Sb(e,t){let n=wb(Db(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function Cb(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Tb(r,t.markerOffset);return}e.scrollTop=Eb(e.scrollHeight,t.distanceFromBottom)}function wb(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 Tb(e,t){return e-t}function Eb(e,t){return Math.max(0,e-t)}function Db(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 Ob=600,kb=1;function Ab(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:jb(e)||Mb(e)}function jb(e){return e.scrollTop<(e.topThreshold??Math.max(Ob,e.clientHeight))}function Mb(e){return e.scrollHeight<=e.clientHeight+kb}var Nb=`pi-webui:chat-scroll:`,Pb=180,Fb=48,Ib=2,Lb={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)}},Rb={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},zb=class{constructor(e=Lb,t=Rb){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=Pb){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=Ib){if(e===``||t===void 0||!Hb(t))return`skipped`;try{if(Wb(t,r))return this.storage.setItem(Bb(e),JSON.stringify({mode:`bottom`})),`saved`;let i=Kb(t,n);if(i===void 0)return`skipped`;let a=Gb(t,i);return this.storage.setItem(Bb(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||!Hb(t))return{status:`skipped`};let i=qb(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(Bb(e));if(t===null||t===``)return;let n=JSON.parse(t);return Vb(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!Hb(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function Bb(e){return`${Nb}${e}`}function Vb(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 Hb(e){return e.clientHeight>0&&e.scrollHeight>0}function Ub(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Wb(e,t=Fb){return Ub(e)<t}function Gb(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:Jb(t)??``,offset:t.getBoundingClientRect().top-n}}function Kb(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(Jb(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 qb(e,t){return e.find(e=>Jb(e)===t)}function Jb(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}function Yb(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?Xb(r/i):0,viewportRatio:Xb(n/t),visible:!0}}function Xb(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}var Zb=5e-5;function Qb(e,t,n=Zb){return e.visible===t.visible&&Math.abs(e.scrollRatio-t.scrollRatio)<n&&Math.abs(e.viewportRatio-t.viewportRatio)<n}function $b(e,t){return Xb(e*(1-t))}function ex(e,t,n,r){return r<=0?0:Xb((e-t+n)/r)}var tx=22,nx=2;function rx(e,t){if(e.length===0)return[];let n=Number.isFinite(t)?Math.max(0,t):0,r=Math.max(0,n-tx),i=e.map((e,t)=>({index:t,desiredTop:Xb(e.topRatio)*n-tx/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*tx+(i.length-1)*nx>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 ix(e){if(typeof e!=`object`||!e||!(`ratio`in e))return;let t=e.ratio;if(!(typeof t!=`number`||!Number.isFinite(t)))return Xb(t)}function ax(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 ox(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function sx(e){return!Number.isFinite(e)||e===0?`$0.0000`:`$${e.toFixed(4)}`}function cx(e){return Number.isFinite(e)?Math.round(e).toLocaleString():`0`}function lx(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 ux(e){let t=[],n=e.tokens;t.push(`Input: ${cx(n.input)}`),t.push(`Output: ${cx(n.output)}`),t.push(`Cache read: ${cx(n.cacheRead)}`),t.push(`Cache write: ${cx(n.cacheWrite)}`),t.push(`Total: ${cx(n.total)}`),e.cost>0&&t.push(`Cost: ${sx(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 ${cx(r.contextWindow)} tokens`)}return t.join(` | `)}function dx(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 fx(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:cx(e.messageCount)}):(i.push({label:`User`,value:cx(n.user)}),i.push({label:`Assistant`,value:cx(n.assistant)}),i.push({label:`Tool calls`,value:cx(n.toolCalls)}),i.push({label:`Tool results`,value:cx(n.toolResults)}),i.push({label:`Total`,value:cx(n.total)}));let a=e.tokens,o=[{label:`Input`,value:cx(a.input)},{label:`Output`,value:cx(a.output)}];a.cacheRead>0&&o.push({label:`Cache read`,value:cx(a.cacheRead)}),a.cacheWrite>0&&o.push({label:`Cache write`,value:cx(a.cacheWrite)}),o.push({label:`Total`,value:cx(a.total)}),e.cost>0&&o.push({label:`Cost`,value:sx(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} / ${lx(s.contextWindow)}`})}return{sessionRows:r,messageRows:i,tokenRows:o}}var px=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=Xb((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=Xb((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=Xb(this._viewportTopRatio()+n);this._dispatchScroll(r)}}_viewportTopRatio(){return $b(this.scrollRatio,this.viewportRatio)}_dispatchScroll(e){let t=Xb(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`
2356
2356
  <div
2357
2357
  class="rail"
2358
2358
  role="scrollbar"
@@ -2386,7 +2386,7 @@ This will delete every archived session on this machine regardless of age or cle
2386
2386
  class=${`marker-dot${r?` user`:` assistant`}${n?` nearest`:``}`}
2387
2387
  ></div>
2388
2388
  </div>
2389
- `}_renderTooltips(){if(!this._hovered)return null;let e=nx(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`
2389
+ `}_renderTooltips(){if(!this._hovered)return null;let e=rx(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`
2390
2390
  <div
2391
2391
  class=${`tooltip ${t.role}${i?` nearest`:``}`}
2392
2392
  style=${`top:${String(r)}px`}
@@ -2524,14 +2524,14 @@ This will delete every archived session on this machine regardless of age or cle
2524
2524
  transition: none;
2525
2525
  }
2526
2526
  }
2527
- `}};B([x({type:Number})],fx.prototype,`scrollRatio`,void 0),B([x({type:Number})],fx.prototype,`viewportRatio`,void 0),B([x({type:Boolean})],fx.prototype,`visible`,void 0),B([x({type:Number})],fx.prototype,`loadedPercent`,void 0),B([x({attribute:!1})],fx.prototype,`markers`,void 0),B([S()],fx.prototype,`_hovered`,void 0),B([S()],fx.prototype,`_nearestIndex`,void 0),B([C(`.rail`)],fx.prototype,`_rail`,void 0),fx=B([b(`chat-minimap`)],fx);var px=class extends kv{constructor(e){if(super(e),this.it=v,e.type!==Dv.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:[]}}};px.directiveName=`unsafeHTML`,px.resultType=1;var mx=Ov(px);function hx(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var gx=hx();function _x(e){gx=e}var vx={exec:()=>null};function yx(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(xx.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var bx=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),xx={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:yx(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:yx(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:yx(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:yx(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:yx(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:yx(e=>RegExp(`^ {0,${e}}>`))},Sx=/^(?:[ \t]*(?:\n|$))+/,Cx=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,wx=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Tx=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ex=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Dx=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ox=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,kx=U(Ox).replace(/bull/g,Dx).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(),Ax=U(Ox).replace(/bull/g,Dx).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(),jx=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Mx=/^[^\n]+/,Nx=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Px=U(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Nx).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Fx=U(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Dx).getRegex(),Ix=`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`,Lx=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Rx=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`,Lx).replace(`tag`,Ix).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),zx=e=>U(jx).replace(`hr`,Tx).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`,Ix).getRegex(),Bx=zx(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Vx=zx(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),Hx={blockquote:U(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Vx).getRegex(),code:Cx,def:Px,fences:wx,heading:Ex,hr:Tx,html:Rx,lheading:kx,list:Fx,newline:Sx,paragraph:Bx,table:vx,text:Mx},Ux=U(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,Tx).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`,Ix).getRegex(),Wx={...Hx,lheading:Ax,table:Ux,paragraph:U(jx).replace(`hr`,Tx).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Ux).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`,Ix).getRegex()},Gx={...Hx,html:U(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Lx).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:vx,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:U(jx).replace(`hr`,Tx).replace(`heading`,` *#{1,6} *[^
2528
- ]`).replace(`lheading`,kx).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},Kx=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,qx=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Jx=/^( {2,}|\\)\n(?!\s*$)/,Yx=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Xx=/[\p{P}\p{S}]/u,Zx=/[\s\p{P}\p{S}]/u,Qx=/[^\s\p{P}\p{S}]/u,$x=U(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Zx).getRegex(),eS=/(?!~)[\p{P}\p{S}]/u,tS=/(?!~)[\s\p{P}\p{S}]/u,nS=/(?:[^\s\p{P}\p{S}]|~)/u,rS=U(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,bx?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),iS=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,aS=U(iS,`u`).replace(/punct/g,Xx).getRegex(),oS=U(iS,`u`).replace(/punct/g,eS).getRegex(),sS=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,cS=U(sS,`gu`).replace(/notPunctSpace/g,Qx).replace(/punctSpace/g,Zx).replace(/punct/g,Xx).getRegex(),lS=U(sS,`gu`).replace(/notPunctSpace/g,nS).replace(/punctSpace/g,tS).replace(/punct/g,eS).getRegex(),uS=U(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Qx).replace(/punctSpace/g,Zx).replace(/punct/g,Xx).getRegex(),dS=U(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Xx).getRegex(),fS=U(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Qx).replace(/punctSpace/g,Zx).replace(/punct/g,Xx).getRegex(),pS=U(/\\(punct)/,`gu`).replace(/punct/g,Xx).getRegex(),mS=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(),hS=U(Lx).replace(`(?:-->|$)`,`-->`).getRegex(),gS=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`,hS).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),_S=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,vS=U(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,_S).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),yS=U(/^!?\[(label)\]\[(ref)\]/).replace(`label`,_S).replace(`ref`,Nx).getRegex(),bS=U(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Nx).getRegex(),xS=U(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,yS).replace(`nolink`,bS).getRegex(),SS=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,CS={_backpedal:vx,anyPunctuation:pS,autolink:mS,blockSkip:rS,br:Jx,code:qx,del:vx,delLDelim:vx,delRDelim:vx,emStrongLDelim:aS,emStrongRDelimAst:cS,emStrongRDelimUnd:uS,escape:Kx,link:vS,nolink:bS,punctuation:$x,reflink:yS,reflinkSearch:xS,tag:gS,text:Yx,url:vx},wS={...CS,link:U(/^!?\[(label)\]\((.*?)\)/).replace(`label`,_S).getRegex(),reflink:U(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,_S).getRegex()},TS={...CS,emStrongRDelimAst:lS,emStrongLDelim:oS,delLDelim:dS,delRDelim:fS,url:U(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,SS).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`,SS).getRegex()},ES={...TS,br:U(Jx).replace(`{2,}`,`*`).getRegex(),text:U(TS.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},DS={normal:Hx,gfm:Wx,pedantic:Gx},OS={normal:CS,gfm:TS,breaks:ES,pedantic:wS},kS={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},AS=e=>kS[e];function jS(e,t){if(t){if(xx.escapeTest.test(e))return e.replace(xx.escapeReplace,AS)}else if(xx.escapeTestNoEncode.test(e))return e.replace(xx.escapeReplaceNoEncode,AS);return e}function MS(e){try{e=encodeURI(e).replace(xx.percentDecode,`%`)}catch{return null}return e}function NS(e,t){let n=e.replace(xx.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(xx.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(xx.slashPipe,`|`);return n}function PS(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 FS(e){let t=e.split(`
2529
- `),n=t.length-1;for(;n>=0&&xx.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
2530
- `)}function IS(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 LS(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 RS(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 zS(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
2527
+ `}};B([x({type:Number})],px.prototype,`scrollRatio`,void 0),B([x({type:Number})],px.prototype,`viewportRatio`,void 0),B([x({type:Boolean})],px.prototype,`visible`,void 0),B([x({type:Number})],px.prototype,`loadedPercent`,void 0),B([x({attribute:!1})],px.prototype,`markers`,void 0),B([S()],px.prototype,`_hovered`,void 0),B([S()],px.prototype,`_nearestIndex`,void 0),B([C(`.rail`)],px.prototype,`_rail`,void 0),px=B([b(`chat-minimap`)],px);var mx=class extends kv{constructor(e){if(super(e),this.it=v,e.type!==Dv.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:[]}}};mx.directiveName=`unsafeHTML`,mx.resultType=1;var hx=Ov(mx);function gx(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var _x=gx();function vx(e){_x=e}var yx={exec:()=>null};function bx(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(Sx.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var xx=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),Sx={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:bx(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:bx(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:bx(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:bx(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:bx(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:bx(e=>RegExp(`^ {0,${e}}>`))},Cx=/^(?:[ \t]*(?:\n|$))+/,wx=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Tx=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ex=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Dx=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ox=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,kx=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ax=U(kx).replace(/bull/g,Ox).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(),jx=U(kx).replace(/bull/g,Ox).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(),Mx=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Nx=/^[^\n]+/,Px=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Fx=U(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Px).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ix=U(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Ox).getRegex(),Lx=`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`,Rx=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,zx=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`,Rx).replace(`tag`,Lx).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Bx=e=>U(Mx).replace(`hr`,Ex).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`,Lx).getRegex(),Vx=Bx(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Hx=Bx(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),Ux={blockquote:U(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Hx).getRegex(),code:wx,def:Fx,fences:Tx,heading:Dx,hr:Ex,html:zx,lheading:Ax,list:Ix,newline:Cx,paragraph:Vx,table:yx,text:Nx},Wx=U(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,Ex).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`,Lx).getRegex(),Gx={...Ux,lheading:jx,table:Wx,paragraph:U(Mx).replace(`hr`,Ex).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Wx).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`,Lx).getRegex()},Kx={...Ux,html:U(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Rx).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:yx,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:U(Mx).replace(`hr`,Ex).replace(`heading`,` *#{1,6} *[^
2528
+ ]`).replace(`lheading`,Ax).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},qx=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Jx=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Yx=/^( {2,}|\\)\n(?!\s*$)/,Xx=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Zx=/[\p{P}\p{S}]/u,Qx=/[\s\p{P}\p{S}]/u,$x=/[^\s\p{P}\p{S}]/u,eS=U(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Qx).getRegex(),tS=/(?!~)[\p{P}\p{S}]/u,nS=/(?!~)[\s\p{P}\p{S}]/u,rS=/(?:[^\s\p{P}\p{S}]|~)/u,iS=U(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,xx?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),aS=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,oS=U(aS,`u`).replace(/punct/g,Zx).getRegex(),sS=U(aS,`u`).replace(/punct/g,tS).getRegex(),cS=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,lS=U(cS,`gu`).replace(/notPunctSpace/g,$x).replace(/punctSpace/g,Qx).replace(/punct/g,Zx).getRegex(),uS=U(cS,`gu`).replace(/notPunctSpace/g,rS).replace(/punctSpace/g,nS).replace(/punct/g,tS).getRegex(),dS=U(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,$x).replace(/punctSpace/g,Qx).replace(/punct/g,Zx).getRegex(),fS=U(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Zx).getRegex(),pS=U(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,$x).replace(/punctSpace/g,Qx).replace(/punct/g,Zx).getRegex(),mS=U(/\\(punct)/,`gu`).replace(/punct/g,Zx).getRegex(),hS=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(),gS=U(Rx).replace(`(?:-->|$)`,`-->`).getRegex(),_S=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`,gS).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),vS=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,yS=U(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,vS).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),bS=U(/^!?\[(label)\]\[(ref)\]/).replace(`label`,vS).replace(`ref`,Px).getRegex(),xS=U(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Px).getRegex(),SS=U(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,bS).replace(`nolink`,xS).getRegex(),CS=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,wS={_backpedal:yx,anyPunctuation:mS,autolink:hS,blockSkip:iS,br:Yx,code:Jx,del:yx,delLDelim:yx,delRDelim:yx,emStrongLDelim:oS,emStrongRDelimAst:lS,emStrongRDelimUnd:dS,escape:qx,link:yS,nolink:xS,punctuation:eS,reflink:bS,reflinkSearch:SS,tag:_S,text:Xx,url:yx},TS={...wS,link:U(/^!?\[(label)\]\((.*?)\)/).replace(`label`,vS).getRegex(),reflink:U(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,vS).getRegex()},ES={...wS,emStrongRDelimAst:uS,emStrongLDelim:sS,delLDelim:fS,delRDelim:pS,url:U(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,CS).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`,CS).getRegex()},DS={...ES,br:U(Yx).replace(`{2,}`,`*`).getRegex(),text:U(ES.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},OS={normal:Ux,gfm:Gx,pedantic:Kx},kS={normal:wS,gfm:ES,breaks:DS,pedantic:TS},AS={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},jS=e=>AS[e];function MS(e,t){if(t){if(Sx.escapeTest.test(e))return e.replace(Sx.escapeReplace,jS)}else if(Sx.escapeTestNoEncode.test(e))return e.replace(Sx.escapeReplaceNoEncode,jS);return e}function NS(e){try{e=encodeURI(e).replace(Sx.percentDecode,`%`)}catch{return null}return e}function PS(e,t){let n=e.replace(Sx.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Sx.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(Sx.slashPipe,`|`);return n}function FS(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 IS(e){let t=e.split(`
2529
+ `),n=t.length-1;for(;n>=0&&Sx.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
2530
+ `)}function LS(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 RS(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 zS(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 BS(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
2531
2531
  `).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(`
2532
- `)}var BS=class{options;rules;lexer;constructor(e){this.options=e||gx}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]:FS(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=zS(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=PS(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:PS(t[0],`
2533
- `),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:PS(t[0],`
2534
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=PS(t[0],`
2532
+ `)}var VS=class{options;rules;lexer;constructor(e){this.options=e||_x}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]:IS(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=BS(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=FS(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:FS(t[0],`
2533
+ `),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:FS(t[0],`
2534
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=FS(t[0],`
2535
2535
  `).split(`
2536
2536
  `),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(`
2537
2537
  `),c=s.replace(this.rules.other.blockquoteSetextReplace,`
@@ -2542,20 +2542,20 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
2542
2542
  `),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+`
2543
2543
  `+e.join(`
2544
2544
  `),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(`
2545
- `);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=LS(t[2].split(`
2545
+ `);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=RS(t[2].split(`
2546
2546
  `,1)[0],t[1].length),l=e.split(`
2547
2547
  `,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+`
2548
2548
  `,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(`
2549
2549
  `,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+=`
2550
2550
  `+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+=`
2551
2551
  `+l}u=!l.trim(),r+=p+`
2552
- `,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=FS(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:PS(t[0],`
2553
- `),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=NS(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
2554
- `):[],a={type:`table`,raw:PS(t[0],`
2555
- `),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(NS(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:PS(t[0],`
2552
+ `,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=IS(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:FS(t[0],`
2553
+ `),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=PS(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
2554
+ `):[],a={type:`table`,raw:FS(t[0],`
2555
+ `),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(PS(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:FS(t[0],`
2556
2556
  `),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)===`
2557
- `?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=PS(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=IS(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)),RS(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 RS(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}}}},VS=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||gx,this.options.tokenizer=this.options.tokenizer||new BS,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:xx,block:DS.normal,inline:OS.normal};this.options.pedantic?(t.block=DS.pedantic,t.inline=OS.pedantic):this.options.gfm&&(t.block=DS.gfm,this.options.breaks?t.inline=OS.breaks:t.inline=OS.gfm),this.tokenizer.rules=t}static get rules(){return{block:DS,inline:OS}}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(xx.carriageReturn,`
2558
- `),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(xx.tabCharGlobal,` `).replace(xx.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+=`
2557
+ `?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=FS(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=LS(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)),zS(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 zS(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}}}},HS=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||_x,this.options.tokenizer=this.options.tokenizer||new VS,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:Sx,block:OS.normal,inline:kS.normal};this.options.pedantic?(t.block=OS.pedantic,t.inline=kS.pedantic):this.options.gfm&&(t.block=OS.gfm,this.options.breaks?t.inline=kS.breaks:t.inline=kS.gfm),this.tokenizer.rules=t}static get rules(){return{block:OS,inline:kS}}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(Sx.carriageReturn,`
2558
+ `),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(Sx.tabCharGlobal,` `).replace(Sx.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+=`
2559
2559
  `: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(`
2560
2560
  `)?``:`
2561
2561
  `)+i.raw,n.text+=`
@@ -2568,9 +2568,9 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
2568
2568
  `+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(`
2569
2569
  `)?``:`
2570
2570
  `)+i.raw,n.text+=`
2571
- `+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)}},HS=class{options;parser;constructor(e){this.options=e||gx}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(xx.notSpaceStart)?.[0],i=e.replace(xx.endingNewline,``)+`
2572
- `;return r?`<pre><code class="language-`+jS(r)+`">`+(n?i:jS(i,!0))+`</code></pre>
2573
- `:`<pre><code>`+(n?i:jS(i,!0))+`</code></pre>
2571
+ `+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)}},US=class{options;parser;constructor(e){this.options=e||_x}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Sx.notSpaceStart)?.[0],i=e.replace(Sx.endingNewline,``)+`
2572
+ `;return r?`<pre><code class="language-`+MS(r)+`">`+(n?i:MS(i,!0))+`</code></pre>
2573
+ `:`<pre><code>`+(n?i:MS(i,!0))+`</code></pre>
2574
2574
  `}blockquote({tokens:e}){return`<blockquote>
2575
2575
  ${this.parser.parse(e)}</blockquote>
2576
2576
  `}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
@@ -2586,19 +2586,19 @@ ${this.parser.parse(e)}</blockquote>
2586
2586
  `}tablerow({text:e}){return`<tr>
2587
2587
  ${e}</tr>
2588
2588
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
2589
- `}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>${jS(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=MS(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+jS(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=MS(e);if(i===null)return jS(n);e=i;let a=`<img src="${e}" alt="${jS(n)}"`;return t&&(a+=` title="${jS(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:jS(e.text)}},US=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}},WS=class e{options;renderer;textRenderer;constructor(e){this.options=e||gx,this.options.renderer=this.options.renderer||new HS,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new US}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}},GS=class{options;block;constructor(e){this.options=e||gx}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?VS.lex:VS.lexInline}provideParser(e=this.block){return e?WS.parse:WS.parseInline}},KS=new class{defaults=hx();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=WS;Renderer=HS;TextRenderer=US;Lexer=VS;Tokenizer=BS;Hooks=GS;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 HS(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 BS(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 GS;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];GS.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&GS.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 VS.lex(e,t??this.defaults)}parser(e,t){return WS.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?VS.lex:VS.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?WS.parse:WS.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?VS.lex:VS.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?WS.parse:WS.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+=`
2590
- Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+jS(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function W(e,t){return KS.parse(e,t)}W.options=W.setOptions=function(e){return KS.setOptions(e),W.defaults=KS.defaults,_x(W.defaults),W},W.getDefaults=hx,W.defaults=gx,W.use=function(...e){return KS.use(...e),W.defaults=KS.defaults,_x(W.defaults),W},W.walkTokens=function(e,t){return KS.walkTokens(e,t)},W.parseInline=KS.parseInline,W.Parser=WS,W.parser=WS.parse,W.Renderer=HS,W.TextRenderer=US,W.Lexer=VS,W.lexer=VS.lex,W.Tokenizer=BS,W.Hooks=GS,W.parse=W,W.options,W.setOptions,W.use,W.walkTokens,W.parseInline,WS.parse,VS.lex;var qS=new W.Renderer;qS.html=({text:e})=>ZS(e);var JS=300,YS=new Map;function XS(e,t={}){let n=t.cache!==!1;if(n){let t=YS.get(e);if(t!==void 0)return t}let r=QS(W.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:qS}));if(!n)return r;if(YS.set(e,r),YS.size>JS){let e=YS.keys().next().value;e!==void 0&&YS.delete(e)}return r}function ZS(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function QS(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`)&&!$S(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),t.innerHTML}function $S(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var eC=class extends y{constructor(...e){super(...e),this.text=``,this.live=!1,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}>${mx(XS(this.text,{cache:!this.live}))}</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 mb(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=Hm}};B([x()],eC.prototype,`text`,void 0),B([x({type:Boolean})],eC.prototype,`live`,void 0),eC=B([b(`formatted-text`)],eC);var tC=180,nC=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=iC(e.args),n=oC(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:sC(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=rC(e,t);return g`
2589
+ `}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>${MS(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=NS(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+MS(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=NS(e);if(i===null)return MS(n);e=i;let a=`<img src="${e}" alt="${MS(n)}"`;return t&&(a+=` title="${MS(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:MS(e.text)}},WS=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}},GS=class e{options;renderer;textRenderer;constructor(e){this.options=e||_x,this.options.renderer=this.options.renderer||new US,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new WS}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}},KS=class{options;block;constructor(e){this.options=e||_x}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?HS.lex:HS.lexInline}provideParser(e=this.block){return e?GS.parse:GS.parseInline}},qS=new class{defaults=gx();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=GS;Renderer=US;TextRenderer=WS;Lexer=HS;Tokenizer=VS;Hooks=KS;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 US(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 VS(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 KS;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];KS.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&KS.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 HS.lex(e,t??this.defaults)}parser(e,t){return GS.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?HS.lex:HS.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?GS.parse:GS.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?HS.lex:HS.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?GS.parse:GS.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+=`
2590
+ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+MS(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function W(e,t){return qS.parse(e,t)}W.options=W.setOptions=function(e){return qS.setOptions(e),W.defaults=qS.defaults,vx(W.defaults),W},W.getDefaults=gx,W.defaults=_x,W.use=function(...e){return qS.use(...e),W.defaults=qS.defaults,vx(W.defaults),W},W.walkTokens=function(e,t){return qS.walkTokens(e,t)},W.parseInline=qS.parseInline,W.Parser=GS,W.parser=GS.parse,W.Renderer=US,W.TextRenderer=WS,W.Lexer=HS,W.lexer=HS.lex,W.Tokenizer=VS,W.Hooks=KS,W.parse=W,W.options,W.setOptions,W.use,W.walkTokens,W.parseInline,GS.parse,HS.lex;var JS=new W.Renderer;JS.html=({text:e})=>QS(e);var YS=300,XS=new Map;function ZS(e,t={}){let n=t.cache!==!1;if(n){let t=XS.get(e);if(t!==void 0)return t}let r=$S(W.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:JS}));if(!n)return r;if(XS.set(e,r),XS.size>YS){let e=XS.keys().next().value;e!==void 0&&XS.delete(e)}return r}function QS(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function $S(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`)&&!eC(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),t.innerHTML}function eC(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var tC=class extends y{constructor(...e){super(...e),this.text=``,this.live=!1,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}>${hx(ZS(this.text,{cache:!this.live}))}</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 mb(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=Hm}};B([x()],tC.prototype,`text`,void 0),B([x({type:Boolean})],tC.prototype,`live`,void 0),tC=B([b(`formatted-text`)],tC);var nC=180,rC=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=aC(e.args),n=sC(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:cC(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=iC(e,t);return g`
2591
2591
  <section class=${`tool-card ${e.status}`}>
2592
2592
  <div class="tool-header">
2593
2593
  <div class="tool-title">
2594
- <span class="status-icon" aria-hidden="true">${dC(e.status)}</span>
2594
+ <span class="status-icon" aria-hidden="true">${fC(e.status)}</span>
2595
2595
  <strong>${e.toolName}</strong>
2596
2596
  ${this.renderHeaderTarget(l)}
2597
2597
  </div>
2598
2598
  <div class="tool-meta">
2599
- ${aC(e)===void 0?null:g`<span>${aC(e)}</span>`}
2599
+ ${oC(e)===void 0?null:g`<span>${oC(e)}</span>`}
2600
2600
  ${a===void 0?null:g`<span class="diff-stats"><b class="added">+${a.added}</b><span>/</span><b class="removed">-${a.removed}</b></span>`}
2601
- <span class="status-label">${fC(e.status)}</span>
2601
+ <span class="status-label">${pC(e.status)}</span>
2602
2602
  </div>
2603
2603
  </div>
2604
2604
 
@@ -2623,7 +2623,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2623
2623
  `}
2624
2624
  </details>
2625
2625
  `}renderDiffBody(e,t,n){let r=e.split(`
2626
- `),i=!this.showFullDiff&&r.length>tC,a=i?r.slice(0,tC):r;return g`
2626
+ `),i=!this.showFullDiff&&r.length>nC,a=i?r.slice(0,nC):r;return g`
2627
2627
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
2628
2628
  <summary>
2629
2629
  <span>${t}</span>
@@ -2634,7 +2634,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2634
2634
  <span>${i?`Showing ${String(a.length)} of ${String(r.length)} lines`:`Full diff`}</span>
2635
2635
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?`Copied`:`Copy diff`}</button>
2636
2636
  </div>
2637
- <pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${cC(e)}>${e}</span>`)}</code></pre>
2637
+ <pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${lC(e)}>${e}</span>`)}</code></pre>
2638
2638
  ${i?g`
2639
2639
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
2640
2640
  Show all ${String(r.length)} diff lines
@@ -2685,23 +2685,23 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2685
2685
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
2686
2686
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
2687
2687
  .show-more { justify-self: start; }
2688
- `}};B([x({attribute:!1})],nC.prototype,`execution`,void 0),B([S()],nC.prototype,`showFullDiff`,void 0),B([S()],nC.prototype,`copied`,void 0),B([S()],nC.prototype,`diffOpen`,void 0),nC=B([b(`tool-execution-view`)],nC);function rC(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=hC(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function iC(e){return hC(e,`path`)??hC(e,`file_path`)}function aC(e){if(e.toolName!==`edit`)return;let t=mC(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof mC(e.args,`oldText`)==`string`&&typeof mC(e.args,`newText`)==`string`)return`1 edit`}function oC(e){return hC(e,`diff`)}function sC(e){let t=0,n=0;for(let r of e.split(`
2689
- `))lC(r)?t++:uC(r)&&n++;return{added:t,removed:n}}function cC(e){return lC(e)?`added`:uC(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function lC(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function uC(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function dC(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function fC(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function pC(e){return typeof e==`object`&&!!e}function mC(e,t){return pC(e)?e[t]:void 0}function hC(e,t){let n=mC(e,t);return typeof n==`string`?n:void 0}var gC=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),_C=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function vC(e){return g`
2688
+ `}};B([x({attribute:!1})],rC.prototype,`execution`,void 0),B([S()],rC.prototype,`showFullDiff`,void 0),B([S()],rC.prototype,`copied`,void 0),B([S()],rC.prototype,`diffOpen`,void 0),rC=B([b(`tool-execution-view`)],rC);function iC(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=gC(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function aC(e){return gC(e,`path`)??gC(e,`file_path`)}function oC(e){if(e.toolName!==`edit`)return;let t=hC(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof hC(e.args,`oldText`)==`string`&&typeof hC(e.args,`newText`)==`string`)return`1 edit`}function sC(e){return gC(e,`diff`)}function cC(e){let t=0,n=0;for(let r of e.split(`
2689
+ `))uC(r)?t++:dC(r)&&n++;return{added:t,removed:n}}function lC(e){return uC(e)?`added`:dC(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function uC(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function dC(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function fC(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function pC(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function mC(e){return typeof e==`object`&&!!e}function hC(e,t){return mC(e)?e[t]:void 0}function gC(e,t){let n=hC(e,t);return typeof n==`string`?n:void 0}var _C=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),vC=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function yC(e){return g`
2690
2690
  <svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2691
2691
  <path d="m9 18 6-6-6-6"></path>
2692
2692
  </svg>
2693
- `}function yC(){return g`
2693
+ `}function bC(){return g`
2694
2694
  <svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2695
2695
  <path d="M6 6l12 12"></path>
2696
2696
  <path d="M18 6 6 18"></path>
2697
2697
  </svg>
2698
- `}function bC(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 xC(e){return SC(e,0,100)}function SC(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function CC(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 wC(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function TC(e){return e===void 0||e===``?`tool output`:`${e} output`}function EC(e){return`m:${String(e)}`}function DC(e){return`g:${String(e)}`}function OC(e){return`e:${String(e)}`}function kC(e){return`g:${String(e)}`}function AC(e){return e?`msg event-group live`:`msg event-group`}function jC(e){return e?`live events`:`events`}function MC(e,t,n){return e.some(e=>e.source===`server`&&e.messages.length>0)&&t&&n}function NC(e){return e.filter(e=>e.source===`server`&&e.messages.length>0).flatMap(e=>e.messages.map(e=>e.text)).join(`
2698
+ `}function xC(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 SC(e){return CC(e,0,100)}function CC(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function wC(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 TC(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function EC(e){return e===void 0||e===``?`tool output`:`${e} output`}function DC(e){return`m:${String(e)}`}function OC(e){return`g:${String(e)}`}function kC(e){return`e:${String(e)}`}function AC(e){return`g:${String(e)}`}function jC(e){return e?`msg event-group live`:`msg event-group`}function MC(e){return e?`live events`:`events`}function NC(e,t,n){return e.some(e=>e.source===`server`&&e.messages.length>0)&&t&&n}function PC(e){return e.filter(e=>e.source===`server`&&e.messages.length>0).flatMap(e=>e.messages.map(e=>e.text)).join(`
2699
2699
 
2700
- `)}function PC(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 FC(e){return e>=50?`generation-rate very-fast`:e>=30?`generation-rate fast`:e>=15?`generation-rate moderate`:`generation-rate slow`}function IC(e){if(e===void 0)return{afterStatus:[],trailing:[]};let t=e.contextUsage,n=t?t.percent==null?`context ${ix(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${ix(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:`↓ ${ix(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:FC(r.tokensPerSecond)}]],trailing:[{label:`Input tokens`,text:`↑${ix(e.tokens.input)}`},{label:`Output tokens`,text:`↓${ix(e.tokens.output)}`},{label:`Context usage`,text:n},{label:`Session cost`,text:ax(e.cost)},...e.pendingMessageCount>0?[{label:`Queued messages`,text:`${String(e.pendingMessageCount)} queued`}]:[]]}}function LC(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 RC(e){let t=e.meta?.timestamp,n=[t===void 0?void 0:VC(t),HC(e)].filter(e=>e!==void 0&&e!==``);return n.length===0?`No Pi message metadata available`:n.join(` · `)}function zC(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 BC(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
2701
- `)}function VC(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return gC.format(t)}function HC(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 rb,this.scrollController=new zb,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!bC(e)||t===void 0?e!==t:Qd(e)!==Qd(t)}render(){let e=this.groupedMessages();return g`
2700
+ `)}function FC(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 IC(e){return e>=50?`generation-rate very-fast`:e>=30?`generation-rate fast`:e>=15?`generation-rate moderate`:`generation-rate slow`}function LC(e){if(e===void 0)return{afterStatus:[],trailing:[]};let t=e.contextUsage,n=t?t.percent==null?`context ${ax(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${ax(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:`↓ ${ax(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:IC(r.tokensPerSecond)}]],trailing:[{label:`Input tokens`,text:`↑${ax(e.tokens.input)}`},{label:`Output tokens`,text:`↓${ax(e.tokens.output)}`},{label:`Context usage`,text:n},{label:`Session cost`,text:ox(e.cost)},...e.pendingMessageCount>0?[{label:`Queued messages`,text:`${String(e.pendingMessageCount)} queued`}]:[]]}}function RC(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 zC(e){let t=e.meta?.timestamp,n=[t===void 0?void 0:HC(t),UC(e)].filter(e=>e!==void 0&&e!==``);return n.length===0?`No Pi message metadata available`:n.join(` · `)}function BC(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 VC(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
2701
+ `)}function HC(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return _C.format(t)}function UC(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 rb,this.scrollController=new zb,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._minimapVisible=!1,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.minimapViewportFrame!==void 0&&cancelAnimationFrame(this.minimapViewportFrame),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._minimapVisible=!1,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.scheduleMinimapViewportUpdate(),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!xC(e)||t===void 0?e!==t:Qd(e)!==Qd(t)}render(){let e=this.groupedMessages();return g`
2702
2702
  ${this.renderTopNotices()}
2703
2703
  ${this.renderNotificationLiveRegions()}
2704
- <div class="chat-wrap" style=${this._minimapViewport.visible&&this.messages.length>0&&this.messageTotal>0?`--pi-minimap-right:36px`:``}>
2704
+ <div class="chat-wrap" style=${this._minimapVisible&&this.messages.length>0&&this.messageTotal>0?`--pi-minimap-right:36px`:``}>
2705
2705
  ${this.renderConversationRail()}
2706
2706
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${e=>{this.onWheel(e)}} @touchstart=${e=>{this.onTouchStart(e)}} @touchmove=${e=>{this.onTouchMove(e)}}>
2707
2707
  ${this.renderHistoryBoundary()}
@@ -2733,7 +2733,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2733
2733
  aria-expanded=${String(!a)}
2734
2734
  aria-controls="session-notification-list"
2735
2735
  @click=${()=>{this.toggleNotificationTray(e,a)}}
2736
- >${vC(a)}</button>
2736
+ >${yC(a)}</button>
2737
2737
  </div>
2738
2738
  </header>
2739
2739
  <div class="notification-list" id="session-notification-list" ?hidden=${a}>
@@ -2745,7 +2745,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2745
2745
  <div class="notification-metadata">
2746
2746
  <strong class="notification-severity">${n}</strong>
2747
2747
  <span aria-hidden="true">·</span>
2748
- <time datetime=${t.receivedAt}>${_C.format(new Date(t.receivedAt))}</time>
2748
+ <time datetime=${t.receivedAt}>${vC.format(new Date(t.receivedAt))}</time>
2749
2749
  </div>
2750
2750
  <p class="notification-message" dir="auto">${t.message}</p>
2751
2751
  ${r===void 0?null:g`<p class="notification-truncated">${r}</p>`}
@@ -2756,7 +2756,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2756
2756
  title="Dismiss notification"
2757
2757
  ?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
2758
2758
  @click=${()=>{this.dismissNotification(t.id)}}
2759
- >${yC()}</button>
2759
+ >${bC()}</button>
2760
2760
  </article>
2761
2761
  `})}
2762
2762
  </div>
@@ -2764,7 +2764,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2764
2764
  `}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`
2765
2765
  <div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${Bv(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${qd(e)}</span>`)}</div>
2766
2766
  <div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${Bv(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${qd(e)}</span>`)}</div>
2767
- `}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=ef(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=Zd(t.notifications,e),r=Qd(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=Qd(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===Qd(r)&&Jd(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||Qd(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}Jd(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=PC(this.status);return!this.warningsVisible||e.length===0?null:g`
2767
+ `}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=ef(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=Zd(t.notifications,e),r=Qd(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=Qd(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===Qd(r)&&Jd(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||Qd(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}Jd(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=FC(this.status);return!this.warningsVisible||e.length===0?null:g`
2768
2768
  <aside class="session-warnings" role="alert" aria-live="polite">
2769
2769
  ${e.map(e=>{let t=e.dismissId;return g`
2770
2770
  <div class=${e.severityClass}>
@@ -2788,7 +2788,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2788
2788
  </div>
2789
2789
  `})}
2790
2790
  </aside>
2791
- `}renderSessionInfoPopover(){if(!this.sessionInfoOpen)return null;let e=this.status;if(e===void 0)return null;let t=this.messages.length>0?ux(this.messages):void 0,n=dx(e,this.sessionInfo,t);return g`
2791
+ `}renderSessionInfoPopover(){if(!this.sessionInfoOpen)return null;let e=this.status;if(e===void 0)return null;let t=this.messages.length>0?dx(this.messages):void 0,n=fx(e,this.sessionInfo,t);return g`
2792
2792
  <section
2793
2793
  class="session-info-popover"
2794
2794
  id=${`session-info-popover-${this.sessionId}`}
@@ -2845,7 +2845,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2845
2845
  <img class="image-zoom-full" src=${this.zoomedImage.src} alt=${this.zoomedImage.alt} />
2846
2846
  `}
2847
2847
  </dialog>
2848
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=lb(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=IC(this.status),r=LC(this.warningCount,this.warningsExpanded),i=n.trailing.length>0,a=this.status?lx(this.status):``,o=i?`session-info-popover-${this.sessionId}`:void 0;return g`
2848
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=lb(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=LC(this.status),r=RC(this.warningCount,this.warningsExpanded),i=n.trailing.length>0,a=this.status?ux(this.status):``,o=i?`session-info-popover-${this.sessionId}`:void 0;return g`
2849
2849
  <div class=${t?`activity-dock active`:`activity-dock`}>
2850
2850
  ${r===void 0||this.onToggleWarnings===void 0?null:g`
2851
2851
  <button
@@ -2888,7 +2888,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2888
2888
  `:null}
2889
2889
  ${this.renderSessionInfoPopover()}
2890
2890
  </div>
2891
- `}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=CC(this.clientQueuedMessages,this.status?.queuedMessages??[]),t=e.find(e=>e.source===`client`),n=e.filter(e=>e.source===`server`),r=n.length>0,i=MC(e,this.canClearServerQueue,this.onClearServerQueue!==void 0);return g`
2891
+ `}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=wC(this.clientQueuedMessages,this.status?.queuedMessages??[]),t=e.find(e=>e.source===`client`),n=e.filter(e=>e.source===`server`),r=n.length>0,i=NC(e,this.canClearServerQueue,this.onClearServerQueue!==void 0);return g`
2892
2892
  ${t===void 0?null:this.renderQueuedMessageList(t)}
2893
2893
  ${r||i?g`
2894
2894
  <div class="queued-actions">
@@ -2901,7 +2901,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2901
2901
  </div>
2902
2902
  `:null}
2903
2903
  ${n.map(e=>this.renderQueuedMessageList(e))}
2904
- `}async copyAllQueuedMessages(){await mb(NC(CC(this.clientQueuedMessages,this.status?.queuedMessages??[]).filter(e=>e.source===`server`)))}renderQueuedMessageList(e){return g`
2904
+ `}async copyAllQueuedMessages(){await mb(PC(wC(this.clientQueuedMessages,this.status?.queuedMessages??[]).filter(e=>e.source===`server`)))}renderQueuedMessageList(e){return g`
2905
2905
  <aside class="queued-messages" aria-live="polite">
2906
2906
  <div class="queued-header">
2907
2907
  <div class="queued-heading">
@@ -2936,7 +2936,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2936
2936
  <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
2937
2937
  ${this.pendingMessageCount>0?g`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?`message`:`messages`}</small>`:null}
2938
2938
  </aside>
2939
- `: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?xC(this.messages.length/this.conversationDisplayTotal()*100):100,g`
2939
+ `: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?SC(this.messages.length/this.conversationDisplayTotal()*100):100,g`
2940
2940
  <chat-minimap
2941
2941
  .scrollRatio=${this._minimapViewport.scrollRatio}
2942
2942
  .viewportRatio=${this._minimapViewport.viewportRatio}
@@ -2945,7 +2945,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2945
2945
  .markers=${this._minimapMarkers}
2946
2946
  @minimap-scroll-to=${e=>{this._onMinimapScrollTo(e)}}
2947
2947
  ></chat-minimap>
2948
- `)}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 xC(SC(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`
2948
+ `)}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}renderHistoryBoundary(){let e=this.historyRangeLabel();return this.loadingMore?g`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?g`
2949
2949
  <div class="history-boundary">
2950
2950
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
2951
2951
  <span>Scroll up to load earlier messages</span>
@@ -2957,7 +2957,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2957
2957
  ${r?null:this.renderMessageHeader(e,String(t))}
2958
2958
  ${e.parts.map(t=>this.renderPart(t,e,n))}
2959
2959
  </article>
2960
- `}renderToolImageOutput(e,t,n){let r=TC(n);return g`
2960
+ `}renderToolImageOutput(e,t,n){let r=EC(n);return g`
2961
2961
  ${this.renderScrollMarker(this.messageScrollMarkerId(t))}
2962
2962
  <article class="msg tool-image-output" data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
2963
2963
  ${this.renderMessageHeader(e,String(t),r)}
@@ -2965,9 +2965,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2965
2965
  </article>
2966
2966
  `}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`
2967
2967
  ${this.renderScrollMarker(this.groupScrollMarkerId(n))}
2968
- <details class=${AC(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
2968
+ <details class=${jC(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
2969
2969
  <summary>
2970
- <b class="label">${jC(r)}</b>
2970
+ <b class="label">${MC(r)}</b>
2971
2971
  <span>${ub(e)}</span>
2972
2972
  </summary>
2973
2973
  ${a?this.renderMessageGroupBody(e,t,r):null}
@@ -2989,7 +2989,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2989
2989
  <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>
2990
2990
  </div>
2991
2991
  </div>
2992
- `}renderMessageActions(e,t){let n=this.isCopyableMessage(e),r=zC(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`
2992
+ `}renderMessageActions(e,t){let n=this.isCopyableMessage(e),r=BC(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`
2993
2993
  <div class=${`msg-actions${s?` forking`:``}`} aria-label="Message actions">
2994
2994
  ${n?g`
2995
2995
  <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)}}>
@@ -2997,7 +2997,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2997
2997
  </button>
2998
2998
  `:null}
2999
2999
  ${i===void 0?null:g`
3000
- <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,BC(e))}}>
3000
+ <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,VC(e))}}>
3001
3001
  <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">
3002
3002
  <polyline points="15 10 20 15 15 20"></polyline>
3003
3003
  <path d="M4 4v7a4 4 0 0 0 4 4h12"></path>
@@ -3019,7 +3019,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3019
3019
  </div>
3020
3020
  `}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(`
3021
3021
 
3022
- `);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await mb(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=RC(e);return this.messageMetaCache.set(e,n),n}renderPart(e,t,n=!1){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} .live=${n}></formatted-text>`;if(e.type===`thinking`)return g`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text} .live=${n}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
3022
+ `);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await mb(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=zC(e);return this.messageMetaCache.set(e,n),n}renderPart(e,t,n=!1){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} .live=${n}></formatted-text>`;if(e.type===`thinking`)return g`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text} .live=${n}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
3023
3023
  <details class="part skill-invocation">
3024
3024
  <summary><b>[skill]</b> ${e.name}</summary>
3025
3025
  <small>${e.location}</small>
@@ -3030,58 +3030,58 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3030
3030
  <strong>Loaded ${e.name}</strong>
3031
3031
  <small>read ${e.path}</small>
3032
3032
  </div>
3033
- `;if(e.type===`image`){let{src:t,alt:n}=wC(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`
3033
+ `;if(e.type===`image`){let{src:t,alt:n}=TC(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`
3034
3034
  <details class="part" ?open=${e.isError}>
3035
3035
  <summary>${e.isError?`✖`:`✓`} ${e.toolName} result</summary>
3036
3036
  <formatted-text .text=${e.text} .live=${n}></formatted-text>
3037
3037
  </details>
3038
- `: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&&Ab({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){let e=this.chat;return!e||Wb(e)}isAtBottom(){let e=this.chat;return!e||Ub(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 Sb(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(Cb(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=SC(n,0,Math.max(0,e-1));return}this.currentConversationIndex=SC(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 qb(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??qb(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 EC(e)}groupRenderKey(e){return DC(e)}groupAnchorKey(e){return DC(e)}eventAnchorKey(e){return OC(e)}messageScrollMarkerId(e){return EC(e)}groupScrollMarkerId(e){return kC(e)}_updateMinimapViewport(){let e=this.chat;e&&(this._minimapViewport=Xb({scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,scrollTop:e.scrollTop}),this._minimapLoadedPercent=this.hasMore?xC(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=$b(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=rx(e.detail);if(t===void 0)return;let n=this.chat;if(!n)return;let r=n.scrollHeight-n.clientHeight;r<=0||(n.scrollTop=Zb(t/(1-this._minimapViewport.viewportRatio))*r,this.pinnedToBottom=Wb(n))}static{this.styles=Vm}};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 UC=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function WC(e){return typeof e==`string`&&UC.has(e)}function GC(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 KC=`application/octet-stream`,qC=`Failed to read an attachment.`;async function JC(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(QC(i,e))}catch{r=qC}return{attachments:n,...r===void 0?{}:{error:r}}}function YC(e){return e.kind===`image`&&WC(e.mimeType)}function XC(e){return e.every(e=>YC(e))}function ZC(e,t){return XC(t)?e:`folder`}function QC(e,t){return WC(e.type)?{kind:`image`,name:ew(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:ew(e),mimeType:$C(e),data:t,size:e.size}}function $C(e){let t=e.type.trim();return t===``?KC:t}function ew(e){return e.name===``?WC(e.type)?`pasted-image.${GC(e.type)}`:`pasted-file.bin`:e.name}var tw=`pi-webui:attachment-delivery`;function nw(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function rw(e=nw()){try{return e?.getItem(tw)===`folder`?`folder`:`inline`}catch{return`inline`}}function iw(e,t=nw()){try{t?.setItem(tw,e)}catch{}}var aw=`(pointer: coarse), (max-width: 760px)`,ow=`pi-webui.promptEnterPreference`;function sw(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(aw):void 0}function cw(e){return e===`send`||e===`newline`?e:`auto`}function lw(e=mw()){if(e===void 0)return`auto`;try{return cw(e.getItem(ow))}catch{return`auto`}}function uw(e,t=mw()){if(t!==void 0)try{t.setItem(ow,e)}catch{}}function dw(e=sw(),t=lw()){return t===`send`||t!==`newline`&&e?.matches!==!0}function fw(e,t,n=sw()){return e?n?.matches!==!0||t:!1}function pw(e,t=sw(),n=lw()){let r=dw(t,n);return e?!r:r}function mw(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function hw(){return _`
3038
+ `: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.scheduleMinimapViewportUpdate(),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&&Ab({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){let e=this.chat;return!e||Wb(e)}isAtBottom(){let e=this.chat;return!e||Ub(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 Sb(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(Cb(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)})}scheduleMinimapViewportUpdate(){this.minimapViewportFrame===void 0&&(this.minimapViewportFrame=requestAnimationFrame(()=>{this.minimapViewportFrame=void 0,this._updateMinimapViewport()}))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(`.scroll-marker`))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}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 DC(e)}groupRenderKey(e){return OC(e)}groupAnchorKey(e){return OC(e)}eventAnchorKey(e){return kC(e)}messageScrollMarkerId(e){return DC(e)}groupScrollMarkerId(e){return AC(e)}_updateMinimapViewport(){let e=this.chat;if(!e)return;let t=Yb({scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,scrollTop:e.scrollTop});this._minimapLoadedPercent=this.hasMore?SC(this.messages.length/this.conversationDisplayTotal()*100):100,!Qb(this._minimapViewport,t)&&(this._minimapViewport=t,this._minimapVisible===t.visible?this._pushMinimapViewport():this._minimapVisible=t.visible)}_pushMinimapViewport(){let e=this._minimap;e!==void 0&&(e.scrollRatio=this._minimapViewport.scrollRatio,e.viewportRatio=this._minimapViewport.viewportRatio,e.visible=this._minimapViewport.visible,e.loadedPercent=this._minimapLoadedPercent)}_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=ex(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=ix(e.detail);if(t===void 0)return;let n=this.chat;if(!n)return;let r=n.scrollHeight-n.clientHeight;r<=0||(n.scrollTop=Xb(t/(1-this._minimapViewport.viewportRatio))*r,this.pinnedToBottom=Wb(n))}static{this.styles=Vm}};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(`chat-minimap`)],G.prototype,`_minimap`,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,`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,`_minimapVisible`,void 0),G=B([b(`chat-view`)],G);var WC=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function GC(e){return typeof e==`string`&&WC.has(e)}function KC(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 qC=`application/octet-stream`,JC=`Failed to read an attachment.`;async function YC(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push($C(i,e))}catch{r=JC}return{attachments:n,...r===void 0?{}:{error:r}}}function XC(e){return e.kind===`image`&&GC(e.mimeType)}function ZC(e){return e.every(e=>XC(e))}function QC(e,t){return ZC(t)?e:`folder`}function $C(e,t){return GC(e.type)?{kind:`image`,name:tw(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:tw(e),mimeType:ew(e),data:t,size:e.size}}function ew(e){let t=e.type.trim();return t===``?qC:t}function tw(e){return e.name===``?GC(e.type)?`pasted-image.${KC(e.type)}`:`pasted-file.bin`:e.name}var nw=`pi-webui:attachment-delivery`;function rw(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function iw(e=rw()){try{return e?.getItem(nw)===`folder`?`folder`:`inline`}catch{return`inline`}}function aw(e,t=rw()){try{t?.setItem(nw,e)}catch{}}var ow=`(pointer: coarse), (max-width: 760px)`,sw=`pi-webui.promptEnterPreference`;function cw(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(ow):void 0}function lw(e){return e===`send`||e===`newline`?e:`auto`}function uw(e=hw()){if(e===void 0)return`auto`;try{return lw(e.getItem(sw))}catch{return`auto`}}function dw(e,t=hw()){if(t!==void 0)try{t.setItem(sw,e)}catch{}}function fw(e=cw(),t=uw()){return t===`send`||t!==`newline`&&e?.matches!==!0}function pw(e,t,n=cw()){return e?n?.matches!==!0||t:!1}function mw(e,t=cw(),n=uw()){let r=fw(t,n);return e?!r:r}function hw(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function gw(){return _`
3039
3039
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3040
3040
  <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>
3041
3041
  </svg>
3042
- `}function gw(){return _`
3042
+ `}function _w(){return _`
3043
3043
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3044
3044
  <polyline points="4 14 10 14 10 20"></polyline>
3045
3045
  <polyline points="20 10 14 10 14 4"></polyline>
3046
3046
  <line x1="10" y1="14" x2="3" y2="21"></line>
3047
3047
  <line x1="21" y1="3" x2="14" y2="10"></line>
3048
3048
  </svg>
3049
- `}function _w(){return _`
3049
+ `}function vw(){return _`
3050
3050
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3051
3051
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
3052
3052
  <path d="M21 3 11.5 12.5"></path>
3053
3053
  </svg>
3054
- `}function vw(){return _`
3054
+ `}function yw(){return _`
3055
3055
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3056
3056
  <path d="M4 7h11"></path>
3057
3057
  <path d="M4 12h7"></path>
3058
3058
  <path d="M4 17h7"></path>
3059
3059
  <path d="m15 14 5 3-5 3z"></path>
3060
3060
  </svg>
3061
- `}function yw(){return _w()}function bw(){return _`
3061
+ `}function bw(){return vw()}function xw(){return _`
3062
3062
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3063
3063
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
3064
3064
  </svg>
3065
- `}function xw(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return _`
3065
+ `}function Sw(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return _`
3066
3066
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3067
3067
  ${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>`})}
3068
3068
  </svg>
3069
- `}var Sw=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Cw(e){return e===void 0||e===``?`off`:e}function ww(e,t){let n=t.length>=2?t:Sw,r=n.length-1,i=Cw(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var Tw=Ov(class extends kv{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===Dv.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){}}),Ew=class extends y{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
3069
+ `}var Cw=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function ww(e){return e===void 0||e===``?`off`:e}function Tw(e,t){let n=t.length>=2?t:Cw,r=n.length-1,i=ww(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var Ew=Ov(class extends kv{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===Dv.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){}}),Dw=class extends y{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
3070
3070
  <div class="menu">
3071
3071
  ${this.items.map((e,t)=>g`
3072
- <button class=${t===this.selectedIndex?`selected`:``} ${Tw(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
3072
+ <button class=${t===this.selectedIndex?`selected`:``} ${Ew(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
3073
3073
  <strong>${e.insertText}</strong>
3074
3074
  <span>${e.detail}</span>
3075
3075
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
3076
3076
  </button>
3077
3077
  `)}
3078
3078
  </div>
3079
- `:null}static{this.styles=Um}};B([x({attribute:!1})],Ew.prototype,`items`,void 0),B([x({type:Number})],Ew.prototype,`selectedIndex`,void 0),B([x({attribute:!1})],Ew.prototype,`onPick`,void 0),Ew=B([b(`autocomplete-menu`)],Ew);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=rw(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=sw(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=Ow(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&fl(n,this.draft);let r=Ow(this.machineId,this.sessionId);this.draft=r===void 0?``:dl(r),this.currentInputMode=xu(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!Dw(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`
3079
+ `:null}static{this.styles=Um}};B([x({attribute:!1})],Dw.prototype,`items`,void 0),B([x({type:Number})],Dw.prototype,`selectedIndex`,void 0),B([x({attribute:!1})],Dw.prototype,`onPick`,void 0),Dw=B([b(`autocomplete-menu`)],Dw);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=iw(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=cw(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=kw(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&fl(n,this.draft);let r=kw(this.machineId,this.sessionId);this.draft=r===void 0?``:dl(r),this.currentInputMode=xu(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!Ow(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`
3080
3080
  <footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
3081
3081
  <div class="editor-wrap">
3082
3082
  <div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="Message pi" aria-disabled=${this.disabled?`true`:`false`}></div>
3083
3083
  <input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
3084
- <button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${hw()}</button>
3084
+ <button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${gw()}</button>
3085
3085
  ${t?g`<div class="mode-hint">Shell command${e.excludeFromContext?` · excluded from context`:``}</div>`:null}
3086
3086
  ${this.isCompacting&&!t?g`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
3087
3087
  ${this.renderAttachments()}
@@ -3089,21 +3089,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3089
3089
  </div>
3090
3090
  <div class="actions">
3091
3091
  ${this.renderCompactStatus()}
3092
- ${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${i} title="Compact context" aria-label="Compact context" @click=${()=>this.onCompact?.()}>${gw()}<span>Compact</span></button>`}
3093
- <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?vw():_w()}</button>
3094
- ${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`)}}>${yw()}</button>`:null}
3095
- <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?.()}>${bw()}</button>
3092
+ ${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${i} title="Compact context" aria-label="Compact context" @click=${()=>this.onCompact?.()}>${_w()}<span>Compact</span></button>`}
3093
+ <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?yw():vw()}</button>
3094
+ ${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`)}}>${bw()}</button>`:null}
3095
+ <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?.()}>${xw()}</button>
3096
3096
  </div>
3097
3097
  </footer>
3098
- `}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=Ow(this.machineId,this.sessionId);t!==void 0&&fl(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=xu(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: ${Cw(t?.thinkingLevel)}`:`Thinking level: ${Cw(t?.thinkingLevel)}`;return g`
3098
+ `}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=kw(this.machineId,this.sessionId);t!==void 0&&fl(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=xu(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: ${ww(t?.thinkingLevel)}`:`Thinking level: ${ww(t?.thinkingLevel)}`;return g`
3099
3099
  <div class="compact-status" aria-label=${e?`Session defaults`:`Session status`}>
3100
3100
  <button class="select-model" ?disabled=${this.onSelectModel===void 0} title="Select model" @click=${()=>this.onSelectModel?.()}>${r}${n}</button>
3101
- <button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0} title=${i} aria-label=${i} @click=${()=>this.onSelectThinking?.()}>${xw(ww(t?.thinkingLevel,this.availableThinkingLevels))}</button>
3101
+ <button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0} title=${i} aria-label=${i} @click=${()=>this.onSelectThinking?.()}>${Sw(Tw(t?.thinkingLevel,this.availableThinkingLevels))}</button>
3102
3102
  </div>
3103
- `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=XC(this.attachments),t=this.effectiveAttachmentDelivery();return g`
3103
+ `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=ZC(this.attachments),t=this.effectiveAttachmentDelivery();return g`
3104
3104
  <div class="attachments" aria-label="Pending attachments">
3105
3105
  ${this.attachments.map(e=>g`
3106
- <div class=${`attachment-chip ${YC(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
3106
+ <div class=${`attachment-chip ${XC(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
3107
3107
  ${this.renderAttachmentPreview(e)}
3108
3108
  <button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
3109
3109
  </div>
@@ -3118,10 +3118,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3118
3118
  `:null}
3119
3119
  ${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
3120
3120
  </div>
3121
- `}renderAttachmentPreview(e){return YC(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
3122
- <div class="attachment-file-preview" aria-hidden="true">${Pw(e.name)}</div>
3121
+ `}renderAttachmentPreview(e){return XC(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
3122
+ <div class="attachment-file-preview" aria-hidden="true">${Fw(e.name)}</div>
3123
3123
  <span class="attachment-file-name">${e.name}</span>
3124
- `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!XC(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,iw(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){let t=jw(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Mw(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=jw(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 JC(e,Fw);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=>Nw(e))}effectiveAttachmentDelivery(){return ZC(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=>Rw(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=Ow(this.machineId,this.sessionId);t!==void 0&&fl(t,this.draft);let n=xu(this.draft);Cu(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(kw);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(Aw);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=gu(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 hu(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=fw(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 pw(t,this.mobilePromptEnterMedia,lw())?(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=Ow(this.machineId,this.sessionId);e!==void 0&&pl(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=Km}};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 Dw(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 Ow(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return ss(e,t)}function kw(){return[]}function Aw(){return[]}function jw(e){return e===null?[]:Array.from(e.files)}function Mw(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function Nw(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 Pw(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function Fw(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 Iw={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},Lw={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function Rw(e){return xu(e).kind===`normal`?Iw:Lw}var zw=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`
3124
+ `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!ZC(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,aw(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){let t=Mw(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Nw(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=Mw(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 YC(e,Iw);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=>Pw(e))}effectiveAttachmentDelivery(){return QC(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=>zw(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=kw(this.machineId,this.sessionId);t!==void 0&&fl(t,this.draft);let n=xu(this.draft);Cu(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(Aw);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(jw);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=gu(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 hu(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=pw(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 mw(t,this.mobilePromptEnterMedia,uw())?(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=kw(this.machineId,this.sessionId);e!==void 0&&pl(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=Km}};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 Ow(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 kw(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return ss(e,t)}function Aw(){return[]}function jw(){return[]}function Mw(e){return e===null?[]:Array.from(e.files)}function Nw(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function Pw(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 Fw(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function Iw(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 Lw={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},Rw={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function zw(e){return xu(e).kind===`normal`?Lw:Rw}var Bw=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`
3125
3125
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
3126
3126
  <section @mousedown=${e=>{e.stopPropagation()}}>
3127
3127
  <header>
@@ -3137,12 +3137,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3137
3137
  `}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`
3138
3138
  ${t?g`<div class="group-header">${e.group}</div>`:null}
3139
3139
  ${e.items.map(({option:e,index:n})=>g`
3140
- <button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${Tw(n===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
3140
+ <button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${Ew(n===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
3141
3141
  <span>${e.label}</span>
3142
3142
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
3143
3143
  </button>
3144
3144
  `)}
3145
- `})}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=Wm}};B([x()],zw.prototype,`title`,void 0),B([x({type:Boolean})],zw.prototype,`searchable`,void 0),B([x({attribute:!1})],zw.prototype,`options`,void 0),B([x({attribute:!1})],zw.prototype,`selectedValue`,void 0),B([x({attribute:!1})],zw.prototype,`onPick`,void 0),B([x({attribute:!1})],zw.prototype,`onCancel`,void 0),B([S()],zw.prototype,`selectedIndex`,void 0),B([S()],zw.prototype,`query`,void 0),zw=B([b(`command-picker`)],zw);var Bw=class extends y{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
3145
+ `})}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=Wm}};B([x()],Bw.prototype,`title`,void 0),B([x({type:Boolean})],Bw.prototype,`searchable`,void 0),B([x({attribute:!1})],Bw.prototype,`options`,void 0),B([x({attribute:!1})],Bw.prototype,`selectedValue`,void 0),B([x({attribute:!1})],Bw.prototype,`onPick`,void 0),B([x({attribute:!1})],Bw.prototype,`onCancel`,void 0),B([S()],Bw.prototype,`selectedIndex`,void 0),B([S()],Bw.prototype,`query`,void 0),Bw=B([b(`command-picker`)],Bw);var Vw=class extends y{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
3146
3146
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
3147
3147
  <section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3148
3148
  <header>
@@ -3155,7 +3155,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3155
3155
  </header>
3156
3156
  <div class="options">
3157
3157
  ${e.length===0?g`<div class="empty">No actions found.</div>`:e.map((e,t)=>g`
3158
- <button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${Tw(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
3158
+ <button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${Ew(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
3159
3159
  <span class="main">
3160
3160
  <strong>${e.title}</strong>
3161
3161
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
@@ -3168,7 +3168,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3168
3168
  </div>
3169
3169
  </section>
3170
3170
  </div>
3171
- `}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 Vw(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=Gm}};B([x({attribute:!1})],Bw.prototype,`actions`,void 0),B([x({attribute:!1})],Bw.prototype,`onRun`,void 0),B([x({attribute:!1})],Bw.prototype,`onCancel`,void 0),B([C(`input`)],Bw.prototype,`input`,void 0),B([S()],Bw.prototype,`queryText`,void 0),B([S()],Bw.prototype,`selectedIndex`,void 0),Bw=B([b(`action-palette`)],Bw);function Vw(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 Hw=class extends y{render(){let e=this.state;return e===void 0?null:g`
3171
+ `}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 Hw(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=Gm}};B([x({attribute:!1})],Vw.prototype,`actions`,void 0),B([x({attribute:!1})],Vw.prototype,`onRun`,void 0),B([x({attribute:!1})],Vw.prototype,`onCancel`,void 0),B([C(`input`)],Vw.prototype,`input`,void 0),B([S()],Vw.prototype,`queryText`,void 0),B([S()],Vw.prototype,`selectedIndex`,void 0),Vw=B([b(`action-palette`)],Vw);function Hw(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 Uw=class extends y{render(){let e=this.state;return e===void 0?null:g`
3172
3172
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
3173
3173
  <section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3174
3174
  <header>
@@ -3191,13 +3191,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3191
3191
  <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>
3192
3192
  </div>
3193
3193
  `;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`
3194
- <button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${Ww(e.authType)}</small></button>
3194
+ <button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${Gw(e.authType)}</small></button>
3195
3195
  `)}</div>`}}renderProviderButton(e){return g`
3196
3196
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
3197
- <span>${e.name}${e.status.source===void 0?null:g` <em>${Kw(e)}</em>`}</span>
3198
- <small>${e.id} · ${Ww(e.authType)}</small>
3197
+ <span>${e.name}${e.status.source===void 0?null:g` <em>${qw(e)}</em>`}</span>
3198
+ <small>${e.id} · ${Gw(e.authType)}</small>
3199
3199
  </button>
3200
- `}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=Uw(n?.promptType);return g`
3200
+ `}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=Ww(n?.promptType);return g`
3201
3201
  <div class="form">
3202
3202
  ${t.auth===void 0?g`<p>Starting login flow…</p>`:g`
3203
3203
  <p>Open this authorization link:</p>
@@ -3230,7 +3230,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3230
3230
  ${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}
3231
3231
  ${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
3232
3232
  </div>
3233
- `}focusInputIfNeeded(){let e=Gw(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=[Wm,h`
3233
+ `}focusInputIfNeeded(){let e=Kw(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=[Wm,h`
3234
3234
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
3235
3235
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
3236
3236
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -3248,7 +3248,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3248
3248
  .inline-options button { display: grid; gap: 2px; text-align: left; }
3249
3249
  .inline-options small { color: var(--pi-muted); }
3250
3250
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
3251
- `]}};B([x({attribute:!1})],Hw.prototype,`state`,void 0),B([x({attribute:!1})],Hw.prototype,`onChooseMethod`,void 0),B([x({attribute:!1})],Hw.prototype,`onSelectProvider`,void 0),B([x({attribute:!1})],Hw.prototype,`onApiKeyInput`,void 0),B([x({attribute:!1})],Hw.prototype,`onSaveApiKey`,void 0),B([x({attribute:!1})],Hw.prototype,`onLogoutProvider`,void 0),B([x({attribute:!1})],Hw.prototype,`onOAuthInput`,void 0),B([x({attribute:!1})],Hw.prototype,`onOAuthRespond`,void 0),B([x({attribute:!1})],Hw.prototype,`onOAuthCancel`,void 0),B([x({attribute:!1})],Hw.prototype,`onCancel`,void 0),B([C(`input`)],Hw.prototype,`input`,void 0),Hw=B([b(`auth-dialog`)],Hw);function Uw(e){return e===`secret`?`password`:`text`}function Ww(e){return e===`oauth`?`subscription`:`credentials`}function Gw(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 Kw(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 qw=[`openai-completions`,`openai-responses`,`anthropic-messages`,`google-generative-ai`];function Jw(e){return qw.map(t=>({api:t,selected:t===e}))}function Yw(e,t){return e.map(e=>({candidate:e,selected:e.id===t}))}var Xw=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Zw(e){let t=e.providers??{},n=cT(t);return{config:aT(e,{...t,[n]:{api:`openai-completions`}}),providerName:n}}function Qw(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:aT(e,a)}}function $w(e,t,n){let r=e.providers??{};return r[t]===void 0?e:aT(e,{...r,[t]:n})}function eT(e,t){let n=e.providers??{};return n[t]===void 0?e:aT(e,oT(n,t))}function tT(e,t){let n=e.providers?.[t];if(n===void 0)return e;let r=[...n.models??[],{id:``}];return $w(e,t,{...n,models:r})}function nT(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,$w(e,t,{...i,models:o})}function rT(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,$w(e,t,n)}return $w(e,t,{...r,models:a})}function iT(e,t,n,r){let i=n==="default"?sT(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 aT(e,t){return{...e,providers:t}}function oT(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function sT(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function cT(e){let t=`new-provider`,n=1;for(;e[t]!==void 0;)t=`new-provider-${String(n++)}`;return t}var lT={thinkingFormat:`deepseek`,requiresReasoningContentOnAssistantMessages:!0},uT=class extends y{constructor(...e){super(...e),this.modelsApi=so,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`)&&pT(e.get(`machine`))!==this.machineId()&&(this.resetForMachineChange(),this.isConnected&&this.loadConfig())}render(){return g`
3251
+ `]}};B([x({attribute:!1})],Uw.prototype,`state`,void 0),B([x({attribute:!1})],Uw.prototype,`onChooseMethod`,void 0),B([x({attribute:!1})],Uw.prototype,`onSelectProvider`,void 0),B([x({attribute:!1})],Uw.prototype,`onApiKeyInput`,void 0),B([x({attribute:!1})],Uw.prototype,`onSaveApiKey`,void 0),B([x({attribute:!1})],Uw.prototype,`onLogoutProvider`,void 0),B([x({attribute:!1})],Uw.prototype,`onOAuthInput`,void 0),B([x({attribute:!1})],Uw.prototype,`onOAuthRespond`,void 0),B([x({attribute:!1})],Uw.prototype,`onOAuthCancel`,void 0),B([x({attribute:!1})],Uw.prototype,`onCancel`,void 0),B([C(`input`)],Uw.prototype,`input`,void 0),Uw=B([b(`auth-dialog`)],Uw);function Ww(e){return e===`secret`?`password`:`text`}function Gw(e){return e===`oauth`?`subscription`:`credentials`}function Kw(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 qw(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 Jw=[`openai-completions`,`openai-responses`,`anthropic-messages`,`google-generative-ai`];function Yw(e){return Jw.map(t=>({api:t,selected:t===e}))}function Xw(e,t){return e.map(e=>({candidate:e,selected:e.id===t}))}var Zw=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Qw(e){let t=e.providers??{},n=lT(t);return{config:oT(e,{...t,[n]:{api:`openai-completions`}}),providerName:n}}function $w(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:oT(e,a)}}function eT(e,t,n){let r=e.providers??{};return r[t]===void 0?e:oT(e,{...r,[t]:n})}function tT(e,t){let n=e.providers??{};return n[t]===void 0?e:oT(e,sT(n,t))}function nT(e,t){let n=e.providers?.[t];if(n===void 0)return e;let r=[...n.models??[],{id:``}];return eT(e,t,{...n,models:r})}function rT(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,eT(e,t,{...i,models:o})}function iT(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,eT(e,t,n)}return eT(e,t,{...r,models:a})}function aT(e,t,n,r){let i=n==="default"?cT(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 oT(e,t){return{...e,providers:t}}function sT(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function cT(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function lT(e){let t=`new-provider`,n=1;for(;e[t]!==void 0;)t=`new-provider-${String(n++)}`;return t}var uT={thinkingFormat:`deepseek`,requiresReasoningContentOnAssistantMessages:!0},dT=class extends y{constructor(...e){super(...e),this.modelsApi=so,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`)&&mT(e.get(`machine`))!==this.machineId()&&(this.resetForMachineChange(),this.isConnected&&this.loadConfig())}render(){return g`
3252
3252
  <div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
3253
3253
  <section class="dialog" role="dialog" aria-modal="true" aria-labelledby="models-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3254
3254
  <header>
@@ -3259,10 +3259,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3259
3259
  </div>
3260
3260
  <div class="header-actions">
3261
3261
  <button class="icon-button" type="button" title="Reload models configuration" aria-label="Reload models configuration" ?disabled=${this.loading} @click=${()=>{this.loadConfig()}}>
3262
- ${VT()}
3262
+ ${HT()}
3263
3263
  </button>
3264
3264
  <button class="icon-button" type="button" title="Close models configuration" aria-label="Close models configuration" @click=${()=>{this.close()}}>
3265
- ${HT()}
3265
+ ${UT()}
3266
3266
  </button>
3267
3267
  </div>
3268
3268
  </header>
@@ -3280,7 +3280,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3280
3280
  ${this.savedMessage===``?null:g`<span class="saved-message">${this.savedMessage}</span>`}
3281
3281
  </div>
3282
3282
  <button type="button" class="secondary" @click=${()=>{this.configureAuth()}}>
3283
- ${UT()} Authentication
3283
+ ${WT()} Authentication
3284
3284
  </button>
3285
3285
  <button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
3286
3286
  <button type="button" class="primary" ?disabled=${this.saving||this.loading} @click=${()=>{this.saveConfig()}}>
@@ -3301,28 +3301,28 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3301
3301
  </div>
3302
3302
  <div class="tree-actions">
3303
3303
  <button type="button" class="add-provider" @click=${()=>{this.addCustomProvider()}}>
3304
- ${zT()} Add provider
3304
+ ${BT()} Add provider
3305
3305
  </button>
3306
3306
  <button type="button" class="auth-link" @click=${()=>{this.configureAuth()}}>
3307
- ${UT()} Configure authentication
3307
+ ${WT()} Configure authentication
3308
3308
  </button>
3309
3309
  </div>
3310
3310
  </aside>
3311
3311
  `}renderProviderTreeNode(e,t){let n=this.selection?.type===`provider`&&this.selection.providerName===e,r=t.models??[];return g`
3312
3312
  <div class="provider-node">
3313
3313
  <button class="tree-row provider-row ${n?`selected`:``}" type="button" @click=${()=>{this.selectProvider(e)}}>
3314
- ${LT()}
3314
+ ${RT()}
3315
3315
  <span class="tree-label">${e}</span>
3316
3316
  </button>
3317
3317
  ${r.map((t,n)=>g`
3318
3318
  <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)}}>
3319
- ${RT()}
3319
+ ${zT()}
3320
3320
  <span class="tree-label">${t.id.trim()===``?`new model`:t.id}</span>
3321
3321
  ${t.reasoning===!0?g`<span class="thinking-mark" title="Reasoning enabled">T</span>`:null}
3322
3322
  </button>
3323
3323
  `)}
3324
3324
  <button class="tree-row add-model" type="button" @click=${()=>{this.addModel(e)}}>
3325
- ${zT()} <span>Add model</span>
3325
+ ${BT()} <span>Add model</span>
3326
3326
  </button>
3327
3327
  </div>
3328
3328
  `}renderDetail(){let e=this.selection;if(e===void 0)return g`
@@ -3339,16 +3339,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3339
3339
  </div>
3340
3340
  <div class="provider-actions">
3341
3341
  <button type="button" class="secondary" ?disabled=${!r||n?.phase===`discovering`} @click=${()=>{this.discoverModels(e)}}>
3342
- ${n?.phase===`discovering`?GT():VT()} ${n===void 0?`Fetch models`:n.phase===`discovering`?`Fetching models...`:`Refresh models`}
3342
+ ${n?.phase===`discovering`?KT():HT()} ${n===void 0?`Fetch models`:n.phase===`discovering`?`Fetching models...`:`Refresh models`}
3343
3343
  </button>
3344
- <button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${BT()} Delete provider</button>
3344
+ <button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${VT()} Delete provider</button>
3345
3345
  </div>
3346
3346
  </div>
3347
3347
 
3348
3348
  <div class="field-stack provider-name-field">
3349
3349
  <label for="provider-name">Provider name</label>
3350
3350
  <div class="inline-field">
3351
- <input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=hT(e),this.renameError=``}}>
3351
+ <input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=gT(e),this.renameError=``}}>
3352
3352
  <button type="button" class="secondary" ?disabled=${this.providerNameDraft.trim()===``||this.providerNameDraft===e} @click=${()=>{this.renameSelectedProvider(e)}}>Rename</button>
3353
3353
  </div>
3354
3354
  ${this.renameError===``?null:g`<span class="field-error">${this.renameError}</span>`}
@@ -3356,19 +3356,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3356
3356
 
3357
3357
  <div class="field-stack">
3358
3358
  <label for="provider-base-url">Base URL</label>
3359
- <input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:mT(hT(n))})}}>
3359
+ <input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:hT(gT(n))})}}>
3360
3360
  </div>
3361
3361
 
3362
3362
  <div class="field-stack">
3363
3363
  <label for="provider-api-key">API key source</label>
3364
- <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:mT(hT(n))})}}>
3364
+ <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:hT(gT(n))})}}>
3365
3365
  <span class="help-text">Use an environment variable name, prefix a command with <code>!</code>, or configure built-in provider credentials through Authentication.</span>
3366
3366
  </div>
3367
3367
 
3368
3368
  <div class="field-stack">
3369
3369
  <label for="provider-api">API format</label>
3370
- <select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:hT(n)})}}>
3371
- ${Jw(i).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
3370
+ <select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:gT(n)})}}>
3371
+ ${Yw(i).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
3372
3372
  </select>
3373
3373
  </div>
3374
3374
 
@@ -3383,7 +3383,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3383
3383
  </div>
3384
3384
  </details>
3385
3385
  </div>
3386
- `}renderModelDetail(e,t,n,r){let i=this.modelTests[OT(e,r)];return g`
3386
+ `}renderModelDetail(e,t,n,r){let i=this.modelTests[kT(e,r)];return g`
3387
3387
  <div class="detail-content">
3388
3388
  <div class="detail-heading">
3389
3389
  <div>
@@ -3391,35 +3391,35 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3391
3391
  <h2>${n.id.trim()===``?`New model`:n.id}</h2>
3392
3392
  </div>
3393
3393
  <div class="model-actions">
3394
- ${i===void 0?null:g`<span class="connection-state ${i.phase}">${NT(i)}</span>`}
3394
+ ${i===void 0?null:g`<span class="connection-state ${i.phase}">${PT(i)}</span>`}
3395
3395
  <button type="button" class="secondary" ?disabled=${n.id.trim()===``||i?.phase===`testing`} @click=${()=>{this.testModel(e,r)}}>
3396
- ${i?.phase===`testing`?GT():WT()} ${i?.phase===`testing`?`Testing...`:`Test`}
3396
+ ${i?.phase===`testing`?KT():GT()} ${i?.phase===`testing`?`Testing...`:`Test`}
3397
3397
  </button>
3398
- <button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${BT()} Remove</button>
3398
+ <button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${VT()} Remove</button>
3399
3399
  </div>
3400
3400
  </div>
3401
3401
 
3402
- ${i===void 0?null:g`<div class="connection-detail ${i.phase}">${PT(i)}</div>`}
3402
+ ${i===void 0?null:g`<div class="connection-detail ${i.phase}">${FT(i)}</div>`}
3403
3403
 
3404
3404
  <div class="field-grid two-columns">
3405
3405
  ${this.renderModelIdField(e,n,r)}
3406
3406
  <div class="field-stack">
3407
3407
  <label for="model-name">Display name</label>
3408
- <input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:mT(hT(t))})}}>
3408
+ <input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:hT(gT(t))})}}>
3409
3409
  </div>
3410
3410
  </div>
3411
3411
 
3412
3412
  <div class="field-stack">
3413
3413
  <label for="model-api">API override</label>
3414
- <select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:mT(hT(t))})}}>
3414
+ <select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:hT(gT(t))})}}>
3415
3415
  <option value="">Inherit provider API</option>
3416
- ${Jw(n.api).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
3416
+ ${Yw(n.api).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
3417
3417
  </select>
3418
3418
  </div>
3419
3419
 
3420
3420
  <div class="switch-row">
3421
3421
  ${this.renderCheck(`Reasoning / thinking`,n.reasoning===!0,t=>{this.replaceModel(e,r,{...n,reasoning:t||void 0})})}
3422
- ${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?bT(n.input):xT(n.input)})})}
3422
+ ${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?xT(n.input):ST(n.input)})})}
3423
3423
  </div>
3424
3424
 
3425
3425
  ${n.reasoning===!0?g`
@@ -3429,10 +3429,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3429
3429
  <span class="section-label">Thinking configuration</span>
3430
3430
  <p>Map Pi thinking levels to values accepted by this model, or disable a level.</p>
3431
3431
  </div>
3432
- ${this.renderCheck(`DeepSeek thinking compatibility`,ST(n),t=>{this.replaceModel(e,r,CT(n,t))})}
3432
+ ${this.renderCheck(`DeepSeek thinking compatibility`,CT(n),t=>{this.replaceModel(e,r,wT(n,t))})}
3433
3433
  </div>
3434
3434
  <div class="thinking-map">
3435
- ${Xw.map(t=>this.renderThinkingLevel(e,r,n,t))}
3435
+ ${Zw.map(t=>this.renderThinkingLevel(e,r,n,t))}
3436
3436
  </div>
3437
3437
  </section>
3438
3438
  `:null}
@@ -3440,11 +3440,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3440
3440
  <div class="field-grid two-columns">
3441
3441
  <div class="field-stack">
3442
3442
  <label for="context-window">Context window (tokens)</label>
3443
- <input id="context-window" type="number" min="0" inputmode="numeric" .value=${_T(n.contextWindow)} placeholder="128000" @input=${t=>{this.replaceModel(e,r,{...n,contextWindow:vT(hT(t))})}}>
3443
+ <input id="context-window" type="number" min="0" inputmode="numeric" .value=${vT(n.contextWindow)} placeholder="128000" @input=${t=>{this.replaceModel(e,r,{...n,contextWindow:yT(gT(t))})}}>
3444
3444
  </div>
3445
3445
  <div class="field-stack">
3446
3446
  <label for="max-tokens">Max output tokens</label>
3447
- <input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${_T(n.maxTokens)} placeholder="16384" @input=${t=>{this.replaceModel(e,r,{...n,maxTokens:vT(hT(t))})}}>
3447
+ <input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${vT(n.maxTokens)} placeholder="16384" @input=${t=>{this.replaceModel(e,r,{...n,maxTokens:yT(gT(t))})}}>
3448
3448
  </div>
3449
3449
  </div>
3450
3450
 
@@ -3471,14 +3471,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3471
3471
  `}renderModelIdField(e,t,n){let r=this.discoveredModels[e]?.models;if(r===void 0)return g`
3472
3472
  <div class="field-stack">
3473
3473
  <label for="model-id">Model ID <span aria-hidden="true">*</span></label>
3474
- <input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:hT(r)})}}>
3474
+ <input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:gT(r)})}}>
3475
3475
  </div>
3476
3476
  `;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`
3477
3477
  <div class="field-stack">
3478
3478
  <label for="model-id">Model ID <span aria-hidden="true">*</span></label>
3479
- <select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,hT(t))}}>
3479
+ <select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,gT(t))}}>
3480
3480
  ${t.id.trim()===``?g`<option value="" disabled>Select a model</option>`:null}
3481
- ${Yw(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>`)}
3481
+ ${Xw(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>`)}
3482
3482
  </select>
3483
3483
  </div>
3484
3484
  `}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`
@@ -3490,26 +3490,26 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3490
3490
  </div>
3491
3491
  <label class="custom-thinking">
3492
3492
  <span>Custom</span>
3493
- <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`,hT(i))}}>
3493
+ <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`,gT(i))}}>
3494
3494
  </label>
3495
3495
  </div>
3496
3496
  `}renderCostField(e,t,n,r,i){let a=`cost-${t}`;return g`
3497
3497
  <div class="field-stack">
3498
3498
  <label for=${a}>${e}</label>
3499
- <input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${_T(i.cost?.[t])} placeholder="0" @input=${e=>{this.setCost(n,r,i,t,yT(hT(e)))}}>
3499
+ <input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${vT(i.cost?.[t])} placeholder="0" @input=${e=>{this.setCost(n,r,i,t,bT(gT(e)))}}>
3500
3500
  </div>
3501
3501
  `}renderCheck(e,t,n){return g`
3502
3502
  <label class="check-row">
3503
- <input type="checkbox" .checked=${t} @change=${e=>{n(gT(e))}}>
3503
+ <input type="checkbox" .checked=${t} @change=${e=>{n(_T(e))}}>
3504
3504
  <span>${e}</span>
3505
3505
  </label>
3506
3506
  `}renderJsonField(e,t,n,r){let i=`advanced-${t}`,a=this.advancedErrors[t];return g`
3507
3507
  <div class="field-stack">
3508
3508
  <label for=${i}>${e} (JSON object)</label>
3509
- <textarea id=${i} class="mono" rows="4" .value=${TT(n)} @change=${e=>{r(hT(e))}}></textarea>
3509
+ <textarea id=${i} class="mono" rows="4" .value=${ET(n)} @change=${e=>{r(gT(e))}}></textarea>
3510
3510
  ${a===void 0?null:g`<span class="field-error">${a}</span>`}
3511
3511
  </div>
3512
- `}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=dT(await this.modelsApi.config(t));if(!this.isCurrentLoad(e,t))return;this.config=n,this.selection=fT(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: ${IT(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: ${IT(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=OT(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}:MT(t)}}catch(e){a===this.machineId()&&(this.modelTests={...this.modelTests,[i]:{phase:`error`,message:IT(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?jT(this.discoveredModels,e):{...this.discoveredModels,[e]:i},this.error=`Failed to fetch models for ${e}: ${IT(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=Zw(this.config);this.config=e.config,this.selectProvider(e.providerName)}deleteProvider(e){this.clearProviderDiscovery(e),this.config=eT(this.config,e),this.modelTests=kT(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=Qw(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=AT(this.modelTests,e,n),this.selectProvider(n)}replaceProvider(e,t){this.invalidateProviderDiscovery(e),this.config=$w(this.config,e,t),this.modelTests=kT(this.modelTests,e)}addModel(e){let t=this.config.providers?.[e]?.models?.length??0;this.config=tT(this.config,e),this.selectModel(e,t)}deleteModel(e,t){this.config=rT(this.config,e,t),this.modelTests=kT(this.modelTests,e),this.selectProvider(e)}replaceModel(e,t,n){this.config=nT(this.config,e,t,n);let r=OT(e,t);this.modelTests[r]!==void 0&&(this.modelTests=jT(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=jT(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=jT(this.discoveredModels,e))}setThinkingLevel(e,t,n,r,i,a){this.replaceModel(e,t,{...n,thinkingLevelMap:iT(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=wT(n),i=`headers`;if(!r.ok){this.setAdvancedError(i,r.error);return}if(r.value!==void 0&&!ET(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:DT(r.value)})}updateProviderObject(e,t,n,r){let i=wT(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=wT(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=jT(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 pT(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`
3512
+ `}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=fT(await this.modelsApi.config(t));if(!this.isCurrentLoad(e,t))return;this.config=n,this.selection=pT(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: ${LT(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: ${LT(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=kT(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}:NT(t)}}catch(e){a===this.machineId()&&(this.modelTests={...this.modelTests,[i]:{phase:`error`,message:LT(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?MT(this.discoveredModels,e):{...this.discoveredModels,[e]:i},this.error=`Failed to fetch models for ${e}: ${LT(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=Qw(this.config);this.config=e.config,this.selectProvider(e.providerName)}deleteProvider(e){this.clearProviderDiscovery(e),this.config=tT(this.config,e),this.modelTests=AT(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=$w(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=jT(this.modelTests,e,n),this.selectProvider(n)}replaceProvider(e,t){this.invalidateProviderDiscovery(e),this.config=eT(this.config,e,t),this.modelTests=AT(this.modelTests,e)}addModel(e){let t=this.config.providers?.[e]?.models?.length??0;this.config=nT(this.config,e),this.selectModel(e,t)}deleteModel(e,t){this.config=iT(this.config,e,t),this.modelTests=AT(this.modelTests,e),this.selectProvider(e)}replaceModel(e,t,n){this.config=rT(this.config,e,t,n);let r=kT(e,t);this.modelTests[r]!==void 0&&(this.modelTests=MT(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=MT(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=MT(this.discoveredModels,e))}setThinkingLevel(e,t,n,r,i,a){this.replaceModel(e,t,{...n,thinkingLevelMap:aT(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=TT(n),i=`headers`;if(!r.ok){this.setAdvancedError(i,r.error);return}if(r.value!==void 0&&!DT(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:OT(r.value)})}updateProviderObject(e,t,n,r){let i=TT(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=TT(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=MT(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 mT(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`
3513
3513
  :host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
3514
3514
  .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); }
3515
3515
  .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); }
@@ -3617,16 +3617,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3617
3617
  .thinking-row { grid-template-columns: 58px minmax(0, 1fr); }
3618
3618
  .custom-thinking { grid-column: 1 / -1; }
3619
3619
  }
3620
- `}};B([x({attribute:!1})],uT.prototype,`machine`,void 0),B([x({attribute:!1})],uT.prototype,`modelsApi`,void 0),B([x({attribute:!1})],uT.prototype,`onClose`,void 0),B([x({attribute:!1})],uT.prototype,`onConfigureAuth`,void 0),B([x({attribute:!1})],uT.prototype,`onSaved`,void 0),B([S()],uT.prototype,`config`,void 0),B([S()],uT.prototype,`loading`,void 0),B([S()],uT.prototype,`saving`,void 0),B([S()],uT.prototype,`error`,void 0),B([S()],uT.prototype,`savedMessage`,void 0),B([S()],uT.prototype,`selection`,void 0),B([S()],uT.prototype,`providerNameDraft`,void 0),B([S()],uT.prototype,`renameError`,void 0),B([S()],uT.prototype,`advancedErrors`,void 0),B([S()],uT.prototype,`modelTests`,void 0),B([S()],uT.prototype,`discoveredModels`,void 0),uT=B([b(`models-config-dialog`)],uT);function dT(e){return e.providers===void 0?{...e,providers:{}}:e}function fT(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 pT(e){if(!FT(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function mT(e){return e.trim()===``?void 0:e}function hT(e){let t=e.target;return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.value:``}function gT(e){return e.target instanceof HTMLInputElement&&e.target.checked}function _T(e){return e===void 0?``:String(e)}function vT(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isInteger(n)&&n>=0?n:void 0}function yT(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function bT(e){let t=e??[`text`];return t.includes(`image`)?[...t]:[...t,`image`]}function xT(e){let t=(e??[]).filter(e=>e!==`image`);return t.length===0?void 0:t}function ST(e){return e.compat?.thinkingFormat===`deepseek`}function CT(e,t){if(t)return{...e,compat:{...e.compat??{},...lT}};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 wT(e){if(e.trim()===``)return{ok:!0,value:void 0};try{let t=JSON.parse(e);return FT(t)?{ok:!0,value:t}:{ok:!1,error:`Value must be a JSON object.`}}catch(e){return{ok:!1,error:`Invalid JSON: ${IT(e)}`}}}function TT(e){return e===void 0?``:JSON.stringify(e,null,2)}function ET(e){return Object.values(e).every(e=>typeof e==`string`)}function DT(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function OT(e,t){return`${e}\u0000${String(t)}`}function kT(e,t){let n=`${t}\u0000`,r={};for(let[t,i]of Object.entries(e))t.startsWith(n)||(r[t]=i);return r}function AT(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 jT(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function MT(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 NT(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 PT(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 FT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function IT(e){return e instanceof Error?e.message:String(e)}function LT(){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 RT(){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 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="M4 7h16M10 11v6m4-6v6M9 7l1-3h4l1 3m-9 0 1 13h10l1-13"></path></svg>`}function VT(){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 HT(){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 UT(){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 WT(){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 GT(){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=po,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`)&&KT(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`
3620
+ `}};B([x({attribute:!1})],dT.prototype,`machine`,void 0),B([x({attribute:!1})],dT.prototype,`modelsApi`,void 0),B([x({attribute:!1})],dT.prototype,`onClose`,void 0),B([x({attribute:!1})],dT.prototype,`onConfigureAuth`,void 0),B([x({attribute:!1})],dT.prototype,`onSaved`,void 0),B([S()],dT.prototype,`config`,void 0),B([S()],dT.prototype,`loading`,void 0),B([S()],dT.prototype,`saving`,void 0),B([S()],dT.prototype,`error`,void 0),B([S()],dT.prototype,`savedMessage`,void 0),B([S()],dT.prototype,`selection`,void 0),B([S()],dT.prototype,`providerNameDraft`,void 0),B([S()],dT.prototype,`renameError`,void 0),B([S()],dT.prototype,`advancedErrors`,void 0),B([S()],dT.prototype,`modelTests`,void 0),B([S()],dT.prototype,`discoveredModels`,void 0),dT=B([b(`models-config-dialog`)],dT);function fT(e){return e.providers===void 0?{...e,providers:{}}:e}function pT(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 mT(e){if(!IT(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function hT(e){return e.trim()===``?void 0:e}function gT(e){let t=e.target;return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.value:``}function _T(e){return e.target instanceof HTMLInputElement&&e.target.checked}function vT(e){return e===void 0?``:String(e)}function yT(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isInteger(n)&&n>=0?n:void 0}function bT(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function xT(e){let t=e??[`text`];return t.includes(`image`)?[...t]:[...t,`image`]}function ST(e){let t=(e??[]).filter(e=>e!==`image`);return t.length===0?void 0:t}function CT(e){return e.compat?.thinkingFormat===`deepseek`}function wT(e,t){if(t)return{...e,compat:{...e.compat??{},...uT}};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 TT(e){if(e.trim()===``)return{ok:!0,value:void 0};try{let t=JSON.parse(e);return IT(t)?{ok:!0,value:t}:{ok:!1,error:`Value must be a JSON object.`}}catch(e){return{ok:!1,error:`Invalid JSON: ${LT(e)}`}}}function ET(e){return e===void 0?``:JSON.stringify(e,null,2)}function DT(e){return Object.values(e).every(e=>typeof e==`string`)}function OT(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function kT(e,t){return`${e}\u0000${String(t)}`}function AT(e,t){let n=`${t}\u0000`,r={};for(let[t,i]of Object.entries(e))t.startsWith(n)||(r[t]=i);return r}function jT(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 MT(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function NT(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 PT(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 FT(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 IT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function LT(e){return e instanceof Error?e.message:String(e)}function RT(){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 zT(){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 BT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function VT(){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 HT(){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 UT(){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 WT(){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 GT(){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 KT(){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=po,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`)&&qT(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`
3621
3621
  <div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
3622
3622
  <section class="dialog" role="dialog" aria-modal="true" aria-labelledby="skills-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3623
3623
  <header>
3624
3624
  <div class="title-block">
3625
3625
  <h1 id="skills-dialog-title">Skills</h1>
3626
- <span class="target"><code>${XT(this.cwd)}</code> on ${this.machineLabel()}</span>
3626
+ <span class="target"><code>${ZT(this.cwd)}</code> on ${this.machineLabel()}</span>
3627
3627
  </div>
3628
3628
  <button class="icon-button" type="button" title="Close skills configuration" aria-label="Close skills configuration" @click=${()=>{this.close()}}>
3629
- ${dE()}
3629
+ ${fE()}
3630
3630
  </button>
3631
3631
  </header>
3632
3632
 
@@ -3652,21 +3652,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3652
3652
  </div>
3653
3653
  <div class="skill-list-actions">
3654
3654
  <button class="add-skill" type="button" ?aria-pressed=${this.addMode} @click=${()=>{this.openAddMode()}}>
3655
- ${uE()} Add skill
3655
+ ${dE()} Add skill
3656
3656
  </button>
3657
3657
  </div>
3658
3658
  </aside>
3659
- `}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=eE(e,this.updateStatuses);return g`
3659
+ `}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=tE(e,this.updateStatuses);return g`
3660
3660
  <button class="skill-row ${t?`selected`:``}" type="button" @click=${()=>{this.selectSkill(e)}}>
3661
3661
  <span class="skill-indicator ${e.disableModelInvocation?`disabled`:``}" aria-hidden="true"></span>
3662
3662
  <span class="skill-name">${e.name}</span>
3663
3663
  ${n?.state===`update-available`?g`<span class="update-available-mark" title="Update available" aria-label="Update available">↑</span>`:null}
3664
3664
  </button>
3665
- `}renderSkillDetail(e){let t=JT(e),n=$T(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`
3665
+ `}renderSkillDetail(e){let t=YT(e),n=eE(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`
3666
3666
  <div class="detail-content">
3667
3667
  <div class="skill-meta-row">
3668
3668
  <span class="scope-tag ${t}">${t}</span>
3669
- <code class="skill-path" title=${e.filePath}>${YT(e,this.cwd)}</code>
3669
+ <code class="skill-path" title=${e.filePath}>${XT(e,this.cwd)}</code>
3670
3670
  <button
3671
3671
  class="skill-toggle ${o?`enabled`:``}"
3672
3672
  type="button"
@@ -3684,7 +3684,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3684
3684
  <section class="detail-section">
3685
3685
  <h2>Source</h2>
3686
3686
  <a class="source-link" href=${e.install.skillsShUrl} target="_blank" rel="noreferrer" title=${e.install.skillsShUrl}>
3687
- <code>${ZT(e.install.skillsShUrl)} ↗</code>
3687
+ <code>${QT(e.install.skillsShUrl)} ↗</code>
3688
3688
  </a>
3689
3689
  </section>
3690
3690
  `}
@@ -3693,13 +3693,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3693
3693
  <section class="detail-section">
3694
3694
  <h2>Version</h2>
3695
3695
  <div class="version-row">
3696
- <code>${QT(r?.currentVersion??e.install.versionHash)}</code>
3696
+ <code>${$T(r?.currentVersion??e.install.versionHash)}</code>
3697
3697
  ${e.install.canCheckForUpdates?g`
3698
3698
  <button type="button" class="secondary compact-button" ?disabled=${i||a} @click=${()=>{this.checkForUpdates(e)}}>
3699
3699
  ${i?`Checking...`:`Check`}
3700
3700
  </button>
3701
3701
  `:null}
3702
- ${r?.state===`update-available`?g`<code class="update-version">${QT(r.latestVersion)}</code>`:null}
3702
+ ${r?.state===`update-available`?g`<code class="update-version">${$T(r.latestVersion)}</code>`:null}
3703
3703
  ${this.renderUpdateStatus(r,i)}
3704
3704
  ${r?.state===`update-available`?g`
3705
3705
  <button type="button" class="primary compact-button" ?disabled=${a||i} @click=${()=>{this.updateInstalledSkill(e)}}>
@@ -3721,7 +3721,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3721
3721
  <p>${e.description}</p>
3722
3722
  </section>
3723
3723
  </div>
3724
- `}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/`:`${XT(this.cwd)}/.pi/skills/`;return g`
3724
+ `}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/`:`${ZT(this.cwd)}/.pi/skills/`;return g`
3725
3725
  <div class="detail-content add-panel">
3726
3726
  <div class="add-heading">
3727
3727
  <h2>Add Skill</h2>
@@ -3733,7 +3733,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3733
3733
  id="skill-search"
3734
3734
  .value=${this.searchQuery}
3735
3735
  placeholder="e.g. react, testing, deploy"
3736
- @input=${e=>{this.searchQuery=sE(e)}}
3736
+ @input=${e=>{this.searchQuery=cE(e)}}
3737
3737
  @keydown=${e=>{e.key===`Enter`&&(e.preventDefault(),this.searchSkills())}}
3738
3738
  >
3739
3739
  <button type="button" class="primary" ?disabled=${this.searching||this.searchQuery.trim()===``} @click=${()=>{this.searchSkills()}}>
@@ -3755,7 +3755,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3755
3755
 
3756
3756
  ${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>`}
3757
3757
  </div>
3758
- `}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=nE(e.package);return g`
3758
+ `}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=rE(e.package);return g`
3759
3759
  <article class="search-result">
3760
3760
  <div class="search-result-copy">
3761
3761
  <strong>${r.skill??r.repository}</strong>
@@ -3784,7 +3784,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3784
3784
  </div>
3785
3785
  <button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
3786
3786
  </footer>
3787
- `}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=qT(this.selectedFilePath,n.skills)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load skills: ${cE(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=rE(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=cE(e))}finally{this.isCurrentTarget(t)&&(this.togglingPaths=aE(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=cE(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=rE(this.newlyInstalledKeys,tE(n,e)),await this.loadSkills()}catch(e){this.isCurrentTarget(t)&&(this.installError=cE(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=$T(e);return t===void 0?[]:[t]});if(n.length!==0){this.updateError=``,this.checkingUpdateKeys=iE(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=cE(e))}finally{this.isCurrentTarget(t)&&(this.checkingUpdateKeys=oE(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!1))}}}async updateInstalledSkill(e){let t=this.target(),n=e.install,r=$T(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=cE(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=>JT(e)===`project`&&e.install?.skillsShUrl!==void 0},{label:`project`,matches:e=>JT(e)===`project`&&e.install?.skillsShUrl===void 0},{label:`global / skills.sh`,matches:e=>JT(e)===`global`&&e.install?.skillsShUrl!==void 0},{label:`global`,matches:e=>JT(e)===`global`&&e.install?.skillsShUrl===void 0},{label:`path`,matches:e=>JT(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(tE(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 KT(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`
3787
+ `}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=JT(this.selectedFilePath,n.skills)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load skills: ${lE(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=iE(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=lE(e))}finally{this.isCurrentTarget(t)&&(this.togglingPaths=oE(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=lE(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=iE(this.newlyInstalledKeys,nE(n,e)),await this.loadSkills()}catch(e){this.isCurrentTarget(t)&&(this.installError=lE(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=eE(e);return t===void 0?[]:[t]});if(n.length!==0){this.updateError=``,this.checkingUpdateKeys=aE(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=lE(e))}finally{this.isCurrentTarget(t)&&(this.checkingUpdateKeys=sE(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!1))}}}async updateInstalledSkill(e){let t=this.target(),n=e.install,r=eE(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=lE(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=>YT(e)===`project`&&e.install?.skillsShUrl!==void 0},{label:`project`,matches:e=>YT(e)===`project`&&e.install?.skillsShUrl===void 0},{label:`global / skills.sh`,matches:e=>YT(e)===`global`&&e.install?.skillsShUrl!==void 0},{label:`global`,matches:e=>YT(e)===`global`&&e.install?.skillsShUrl===void 0},{label:`path`,matches:e=>YT(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(nE(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 qT(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`
3788
3788
  :host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
3789
3789
  .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); }
3790
3790
  .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); }
@@ -3885,16 +3885,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3885
3885
  .scope-row { align-items: flex-start; flex-direction: column; gap: 6px; }
3886
3886
  .search-result { align-items: flex-start; }
3887
3887
  }
3888
- `}};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 KT(e){if(!lE(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function qT(e,t){return e!==void 0&&t.some(t=>t.filePath===e)?e:t[0]?.filePath}function JT(e){let t=e.sourceInfo.source,n=e.sourceInfo.scope;return n===`user`||t===`user`?`global`:n===`project`||t===`project`?`project`:`path`}function YT(e,t){return JT(e)===`project`&&e.filePath.startsWith(t)?`./${e.filePath.slice(t.length).replace(/^[/\\]/u,``)}`:XT(e.filePath)}function XT(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function ZT(e){return e.replace(/^https?:\/\//u,``)}function QT(e){return e===void 0||e===``?`unknown`:e.slice(0,8)}function $T(e){return e.install===void 0?void 0:`${e.install.scope}\0${e.install.package}`}function eE(e,t){let n=$T(e);return n===void 0?void 0:t[n]}function tE(e,t){return`${e}\0${t}`}function nE(e){let t=e.lastIndexOf(`@`);return t<0?{repository:e,skill:void 0}:{repository:e.slice(0,t),skill:e.slice(t+1)}}function rE(e,t){return new Set([...e,t])}function iE(e,t){return new Set([...e,...t])}function aE(e,t){let n=new Set(e);return n.delete(t),n}function oE(e,t){let n=new Set(e);for(let e of t)n.delete(e);return n}function sE(e){let t=e.target;return t instanceof HTMLInputElement?t.value:``}function cE(e){return e instanceof Error?e.message:String(e)}function lE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function uE(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function dE(){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=vo,this.sessionsApi=So,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`)&&yE(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`
3888
+ `}};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 qT(e){if(!uE(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function JT(e,t){return e!==void 0&&t.some(t=>t.filePath===e)?e:t[0]?.filePath}function YT(e){let t=e.sourceInfo.source,n=e.sourceInfo.scope;return n===`user`||t===`user`?`global`:n===`project`||t===`project`?`project`:`path`}function XT(e,t){return YT(e)===`project`&&e.filePath.startsWith(t)?`./${e.filePath.slice(t.length).replace(/^[/\\]/u,``)}`:ZT(e.filePath)}function ZT(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function QT(e){return e.replace(/^https?:\/\//u,``)}function $T(e){return e===void 0||e===``?`unknown`:e.slice(0,8)}function eE(e){return e.install===void 0?void 0:`${e.install.scope}\0${e.install.package}`}function tE(e,t){let n=eE(e);return n===void 0?void 0:t[n]}function nE(e,t){return`${e}\0${t}`}function rE(e){let t=e.lastIndexOf(`@`);return t<0?{repository:e,skill:void 0}:{repository:e.slice(0,t),skill:e.slice(t+1)}}function iE(e,t){return new Set([...e,t])}function aE(e,t){return new Set([...e,...t])}function oE(e,t){let n=new Set(e);return n.delete(t),n}function sE(e,t){let n=new Set(e);for(let e of t)n.delete(e);return n}function cE(e){let t=e.target;return t instanceof HTMLInputElement?t.value:``}function lE(e){return e instanceof Error?e.message:String(e)}function uE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function dE(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function fE(){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=vo,this.sessionsApi=So,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`)&&bE(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`
3889
3889
  <div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
3890
3890
  <section class="dialog" role="dialog" aria-modal="true" aria-labelledby="plugins-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3891
3891
  <header>
3892
3892
  <div class="title-block">
3893
3893
  <h1 id="plugins-dialog-title">Plugins</h1>
3894
- <span class="target"><code>${bE(this.cwd)}</code> on ${this.machineLabel()}</span>
3894
+ <span class="target"><code>${xE(this.cwd)}</code> on ${this.machineLabel()}</span>
3895
3895
  </div>
3896
3896
  <button class="icon-button" type="button" title="Close Plugins configuration" aria-label="Close Plugins configuration" @click=${()=>{this.close()}}>
3897
- ${EE()}
3897
+ ${DE()}
3898
3898
  </button>
3899
3899
  </header>
3900
3900
 
@@ -3920,20 +3920,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3920
3920
  </div>
3921
3921
  <div class="package-list-actions">
3922
3922
  <button class="add-plugin" type="button" aria-pressed=${String(this.addMode)} @click=${()=>{this.openAddMode()}}>
3923
- ${TE()} Add plugin
3923
+ ${EE()} Add plugin
3924
3924
  </button>
3925
3925
  </div>
3926
3926
  </aside>
3927
- `}renderPackageListItem(e){let t=fE(e),n=!this.addMode&&t===this.selectedKey;return g`
3927
+ `}renderPackageListItem(e){let t=pE(e),n=!this.addMode&&t===this.selectedKey;return g`
3928
3928
  <button class="package-row ${n?`selected`:``}" type="button" aria-pressed=${String(n)} @click=${()=>{this.selectPackage(e)}}>
3929
- <span class="package-indicator" style=${`background:${_E(e.status)}`} aria-hidden="true"></span>
3929
+ <span class="package-indicator" style=${`background:${vE(e.status)}`} aria-hidden="true"></span>
3930
3930
  <span class="package-copy">
3931
3931
  <strong>${e.source}</strong>
3932
- <small>${hE(e)}</small>
3933
- ${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${gE(e)}</small>`}
3932
+ <small>${gE(e)}</small>
3933
+ ${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${_E(e)}</small>`}
3934
3934
  </span>
3935
3935
  </button>
3936
- `}renderPackageDetail(e){let t=fE(e),n=this.busyKey?.endsWith(t)??!1,r=this.busyKey===`reload`,i=!e.disabled;return g`
3936
+ `}renderPackageDetail(e){let t=pE(e),n=this.busyKey?.endsWith(t)??!1,r=this.busyKey===`reload`,i=!e.disabled;return g`
3937
3937
  <div class="detail-content">
3938
3938
  <div class="detail-heading">
3939
3939
  <div class="package-title-row">
@@ -3965,12 +3965,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3965
3965
  </div>
3966
3966
 
3967
3967
  <dl class="metadata-grid">
3968
- <dt>Status</dt><dd style=${`color:${_E(e.status)}`}>${e.status}</dd>
3969
- <dt>Version</dt><dd><code>${gE(e)}</code></dd>
3968
+ <dt>Status</dt><dd style=${`color:${vE(e.status)}`}>${e.status}</dd>
3969
+ <dt>Version</dt><dd><code>${_E(e)}</code></dd>
3970
3970
  <dt>Package</dt><dd><code>${e.packageName??`Unknown`}</code></dd>
3971
- <dt>Resources</dt><dd>${hE(e)}</dd>
3972
- <dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:bE(e.installedPath)}</code></dd>
3973
- <dt>Workspace</dt><dd><code>${bE(this.cwd)}</code></dd>
3971
+ <dt>Resources</dt><dd>${gE(e)}</dd>
3972
+ <dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:xE(e.installedPath)}</code></dd>
3973
+ <dt>Workspace</dt><dd><code>${xE(this.cwd)}</code></dd>
3974
3974
  </dl>
3975
3975
 
3976
3976
  <section class="resource-section">
@@ -3999,7 +3999,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3999
3999
  <div class="detail-content add-panel">
4000
4000
  <div class="add-heading">
4001
4001
  <h2>Add Plugin</h2>
4002
- <code>${this.installScope===`project`?`${bE(this.cwd)}/.pi/agent/{npm,git}`:`~/.pi/agent/{npm,git}`}</code>
4002
+ <code>${this.installScope===`project`?`${xE(this.cwd)}/.pi/agent/{npm,git}`:`~/.pi/agent/{npm,git}`}</code>
4003
4003
  </div>
4004
4004
 
4005
4005
  <div class="field-stack">
@@ -4008,7 +4008,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4008
4008
  id="plugin-source"
4009
4009
  .value=${this.installSource}
4010
4010
  placeholder="npm:@scope/package"
4011
- @input=${e=>{this.installSource=SE(e)}}
4011
+ @input=${e=>{this.installSource=CE(e)}}
4012
4012
  @keydown=${t=>{t.key!==`Enter`||this.installSource.trim()===``||e||(t.preventDefault(),this.installPlugin())}}
4013
4013
  >
4014
4014
  </div>
@@ -4035,7 +4035,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4035
4035
  `}renderFooter(){let e=this.data,t=e?.diagnostics??[],n=this.busyKey!==void 0;return g`
4036
4036
  <footer>
4037
4037
  <div class="footer-summary">
4038
- ${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(xE).join(`
4038
+ ${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(SE).join(`
4039
4039
  `)}>
4040
4040
  ${String(t.length)} diagnostic${t.length===1?``:`s`}
4041
4041
  </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>`}
@@ -4043,7 +4043,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4043
4043
  <button type="button" class="secondary" ?disabled=${this.loading||n} @click=${()=>{this.loadPlugins()}}>Refresh</button>
4044
4044
  <button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
4045
4045
  </footer>
4046
- `}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=pE(this.selectedKey,n.packages)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load plugins: ${CE(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=fE(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=pE(void 0,r.packages),r.packages.length===0&&(this.addMode=!0),this.actionMessage=`Package removed.`):this.actionMessage=vE(e)}catch(e){this.isCurrentTarget(n)&&(this.actionError=CE(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=mE(i.packages,t,n);this.selectedKey=a===void 0?r:fE(a),this.addMode=!1,this.installSource=``,this.actionMessage=`Package installed.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=CE(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=CE(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=>fE(e)===this.selectedKey)}selectPackage(e){this.selectedKey=fE(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 yE(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`
4046
+ `}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=mE(this.selectedKey,n.packages)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load plugins: ${wE(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=pE(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=mE(void 0,r.packages),r.packages.length===0&&(this.addMode=!0),this.actionMessage=`Package removed.`):this.actionMessage=yE(e)}catch(e){this.isCurrentTarget(n)&&(this.actionError=wE(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=hE(i.packages,t,n);this.selectedKey=a===void 0?r:pE(a),this.addMode=!1,this.installSource=``,this.actionMessage=`Package installed.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=wE(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=wE(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=>pE(e)===this.selectedKey)}selectPackage(e){this.selectedKey=pE(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 bE(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`
4047
4047
  :host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
4048
4048
  .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); }
4049
4049
  .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); }
@@ -4145,7 +4145,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4145
4145
  .package-actions { width: 100%; }
4146
4146
  .metadata-grid { grid-template-columns: 96px minmax(0, 1fr); }
4147
4147
  }
4148
- `}};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 fE(e){return`${e.scope}\0${e.source}`}function pE(e,t){return e!==void 0&&t.some(t=>fE(t)===e)?e:t[0]===void 0?void 0:fE(t[0])}function mE(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 hE(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 gE(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 _E(e){return e===`loaded`?`var(--pi-accent)`:e===`installed`?`#d97706`:e===`disabled`?`var(--pi-muted)`:`var(--pi-danger)`}function vE(e){switch(e){case`install`:return`Package installed.`;case`update`:return`Package updated.`;case`disable`:return`Package disabled.`;case`enable`:return`Package enabled.`}}function yE(e){if(!wE(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function bE(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function xE(e){return`${e.type}: ${e.source===void 0?``:`${e.source}: `}${e.message}`}function SE(e){return e.target instanceof HTMLInputElement?e.target.value:``}function CE(e){return e instanceof Error?e.message:String(e)}function wE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function TE(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function EE(){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 DE=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`
4148
+ `}};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 pE(e){return`${e.scope}\0${e.source}`}function mE(e,t){return e!==void 0&&t.some(t=>pE(t)===e)?e:t[0]===void 0?void 0:pE(t[0])}function hE(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 gE(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 _E(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 vE(e){return e===`loaded`?`var(--pi-accent)`:e===`installed`?`#d97706`:e===`disabled`?`var(--pi-muted)`:`var(--pi-danger)`}function yE(e){switch(e){case`install`:return`Package installed.`;case`update`:return`Package updated.`;case`disable`:return`Package disabled.`;case`enable`:return`Package enabled.`}}function bE(e){if(!TE(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function xE(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function SE(e){return`${e.type}: ${e.source===void 0?``:`${e.source}: `}${e.message}`}function CE(e){return e.target instanceof HTMLInputElement?e.target.value:``}function wE(e){return e instanceof Error?e.message:String(e)}function TE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function EE(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function DE(){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 OE=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`
4149
4149
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
4150
4150
  <section @click=${e=>{e.stopPropagation()}}>
4151
4151
  <header>
@@ -4195,7 +4195,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4195
4195
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
4196
4196
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
4197
4197
  button:disabled { opacity: .5; cursor: not-allowed; }
4198
- `}};B([x({attribute:!1})],DE.prototype,`onSubmit`,void 0),B([x({attribute:!1})],DE.prototype,`onCancel`,void 0),B([x()],DE.prototype,`machineId`,void 0),B([S()],DE.prototype,`path`,void 0),B([S()],DE.prototype,`createMissing`,void 0),B([S()],DE.prototype,`suggestions`,void 0),B([S()],DE.prototype,`selected`,void 0),B([S()],DE.prototype,`loading`,void 0),B([C(`input`)],DE.prototype,`pathInput`,void 0),DE=B([b(`project-dialog`)],DE);var OE=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=kE(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`&&AE(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===``||AE(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?AE(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
4198
+ `}};B([x({attribute:!1})],OE.prototype,`onSubmit`,void 0),B([x({attribute:!1})],OE.prototype,`onCancel`,void 0),B([x()],OE.prototype,`machineId`,void 0),B([S()],OE.prototype,`path`,void 0),B([S()],OE.prototype,`createMissing`,void 0),B([S()],OE.prototype,`suggestions`,void 0),B([S()],OE.prototype,`selected`,void 0),B([S()],OE.prototype,`loading`,void 0),B([C(`input`)],OE.prototype,`pathInput`,void 0),OE=B([b(`project-dialog`)],OE);var kE=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=AE(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`&&jE(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===``||jE(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?jE(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
4199
4199
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
4200
4200
  <section @click=${e=>{e.stopPropagation()}}>
4201
4201
  <form @submit=${e=>{this.handleSubmit(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>
@@ -4250,7 +4250,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4250
4250
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
4251
4251
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
4252
4252
  button:disabled { opacity: .5; cursor: not-allowed; }
4253
- `}};B([x({attribute:!1})],OE.prototype,`onSubmit`,void 0),B([x({attribute:!1})],OE.prototype,`onCancel`,void 0),B([x()],OE.prototype,`error`,void 0),B([S()],OE.prototype,`url`,void 0),B([S()],OE.prototype,`name`,void 0),B([S()],OE.prototype,`token`,void 0),B([S()],OE.prototype,`submitting`,void 0),B([C(`input[name='baseUrl']`)],OE.prototype,`urlInput`,void 0),B([C(`input[name='name']`)],OE.prototype,`nameInput`,void 0),OE=B([b(`machine-dialog`)],OE);function kE(e){let t=e.trim();if(t===``)return``;let n=jE(t)??jE(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):ME(t)}function AE(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 jE(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function ME(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 NE={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function PE(e){return e.tone??NE[e.type]}var FE=class extends y{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
4253
+ `}};B([x({attribute:!1})],kE.prototype,`onSubmit`,void 0),B([x({attribute:!1})],kE.prototype,`onCancel`,void 0),B([x()],kE.prototype,`error`,void 0),B([S()],kE.prototype,`url`,void 0),B([S()],kE.prototype,`name`,void 0),B([S()],kE.prototype,`token`,void 0),B([S()],kE.prototype,`submitting`,void 0),B([C(`input[name='baseUrl']`)],kE.prototype,`urlInput`,void 0),B([C(`input[name='name']`)],kE.prototype,`nameInput`,void 0),kE=B([b(`machine-dialog`)],kE);function AE(e){let t=e.trim();if(t===``)return``;let n=ME(t)??ME(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):NE(t)}function jE(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 ME(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function NE(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 PE={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function FE(e){return e.tone??PE[e.type]}var IE=class extends y{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
4254
4254
  <section class="panel" aria-label=${this.heading||`Settings panel`}>
4255
4255
  <header class="section-heading">
4256
4256
  <div class="heading-copy">
@@ -4273,7 +4273,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4273
4273
  <div class="notice-stack" aria-label="Settings notices">
4274
4274
  ${this.notices.map(e=>this.renderNotice(e))}
4275
4275
  </div>
4276
- `}renderNotice(e){let t=PE(e),n=e.role??IE(t),r=e.title;return g`
4276
+ `}renderNotice(e){let t=FE(e),n=e.role??LE(t),r=e.title;return g`
4277
4277
  <article class=${`notice ${t}`} role=${n}>
4278
4278
  ${r===void 0||r===``?v:g`<strong class="notice-title">${r}</strong>`}
4279
4279
  <div class="notice-content">${e.content}</div>
@@ -4306,13 +4306,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4306
4306
  .section-heading { display: grid; gap: 12px; }
4307
4307
  .heading-actions { justify-self: start; }
4308
4308
  }
4309
- `}};B([x()],FE.prototype,`heading`,void 0),B([x({attribute:!1})],FE.prototype,`description`,void 0),B([x()],FE.prototype,`actionLabel`,void 0),B([x()],FE.prototype,`actionTitle`,void 0),B([x({type:Boolean})],FE.prototype,`actionDisabled`,void 0),B([x({attribute:!1})],FE.prototype,`notices`,void 0),B([x({attribute:!1})],FE.prototype,`onAction`,void 0),FE=B([b(`settings-panel-frame`)],FE);function IE(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function LE(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function RE(){return{allowedPathsText:``,uploadDefaultFolder:``}}function zE(){return{command:``,dir:``}}function BE(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(`
4310
- `):``}}function VE(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
4311
- `)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function HE(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function UE(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function WE(e,t){let n=UE(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function GE(e,t={}){let n=qE(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`||JE(e.allowedHostsText),n}function KE(e){let t=YE(e.allowedPathsText),n=XE(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function qE(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 JE(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function YE(e){let t=e.split(`
4312
- `).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!ZE(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function XE(e){let t=e.trim();if(t===``)return``;if(QE(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 ZE(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function QE(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function $E(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var eD=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=LE(),this.machineDraft=RE(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=BE(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=VE(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
4309
+ `}};B([x()],IE.prototype,`heading`,void 0),B([x({attribute:!1})],IE.prototype,`description`,void 0),B([x()],IE.prototype,`actionLabel`,void 0),B([x()],IE.prototype,`actionTitle`,void 0),B([x({type:Boolean})],IE.prototype,`actionDisabled`,void 0),B([x({attribute:!1})],IE.prototype,`notices`,void 0),B([x({attribute:!1})],IE.prototype,`onAction`,void 0),IE=B([b(`settings-panel-frame`)],IE);function LE(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function RE(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function zE(){return{allowedPathsText:``,uploadDefaultFolder:``}}function BE(){return{command:``,dir:``}}function VE(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(`
4310
+ `):``}}function HE(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
4311
+ `)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function UE(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function WE(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function GE(e,t){let n=WE(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function KE(e,t={}){let n=JE(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`||YE(e.allowedHostsText),n}function qE(e){let t=XE(e.allowedPathsText),n=ZE(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function JE(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 YE(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function XE(e){let t=e.split(`
4312
+ `).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!QE(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function ZE(e){let t=e.trim();if(t===``)return``;if($E(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 QE(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function $E(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function eD(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var tD=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=RE(),this.machineDraft=zE(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=VE(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=HE(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
4313
4313
  <settings-panel-frame
4314
4314
  heading="General configuration"
4315
- .description=${$E(this.targetLabel)}
4315
+ .description=${eD(this.targetLabel)}
4316
4316
  actionLabel="Reload"
4317
4317
  .actionDisabled=${this.loading||this.machineLoading}
4318
4318
  .notices=${this.panelNotices()}
@@ -4341,7 +4341,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4341
4341
  <span>Host</span>
4342
4342
  ${this.renderOverrideBadge(`host`)}
4343
4343
  </span>
4344
- <input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:rD(e)})}}>
4344
+ <input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:iD(e)})}}>
4345
4345
  <small>Address the web server should bind to. Leave empty to use PI WEBUI's default.</small>
4346
4346
  </label>
4347
4347
 
@@ -4350,7 +4350,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4350
4350
  <span>Port</span>
4351
4351
  ${this.renderOverrideBadge(`port`)}
4352
4352
  </span>
4353
- <input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:rD(e)})}}>
4353
+ <input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:iD(e)})}}>
4354
4354
  <small>TCP port from 1 to 65535. Leave empty to use PI WEBUI's default.</small>
4355
4355
  </label>
4356
4356
 
@@ -4359,11 +4359,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4359
4359
  <span>Allowed hosts</span>
4360
4360
  ${this.renderOverrideBadge(`allowedHosts`)}
4361
4361
  </span>
4362
- <select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:iD(e)===`all`?`all`:`list`})}}>
4362
+ <select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:aD(e)===`all`?`all`:`list`})}}>
4363
4363
  <option value="list">Only listed hosts</option>
4364
4364
  <option value="all">Allow every host</option>
4365
4365
  </select>
4366
- <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:aD(e)})}}></textarea>
4366
+ <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:oD(e)})}}></textarea>
4367
4367
  <small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
4368
4368
  </div>
4369
4369
 
@@ -4393,7 +4393,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4393
4393
  <span class="field-heading">
4394
4394
  <span>External filesystem roots</span>
4395
4395
  </span>
4396
- <textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:aD(e)})}}></textarea>
4396
+ <textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:oD(e)})}}></textarea>
4397
4397
  <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>
4398
4398
  </label>
4399
4399
 
@@ -4401,7 +4401,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4401
4401
  <span class="field-heading">
4402
4402
  <span>Default upload folder</span>
4403
4403
  </span>
4404
- <input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${Po} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:rD(e)})}}>
4404
+ <input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${Po} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:iD(e)})}}>
4405
4405
  <small>Workspace-relative folder for manual file uploads on ${this.targetLabel}. Leave empty to use PI WEBUI's default <code>${Po}</code>.</small>
4406
4406
  </label>
4407
4407
 
@@ -4419,18 +4419,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4419
4419
  <dl>
4420
4420
  <div><dt>Host</dt><dd>${e.host??g`<span class="muted">127.0.0.1 default</span>`}</dd></div>
4421
4421
  <div><dt>Port</dt><dd>${e.port??g`<span class="muted">8808 default</span>`}</dd></div>
4422
- <div><dt>Allowed hosts</dt><dd>${tD(e.allowedHosts)}</dd></div>
4422
+ <div><dt>Allowed hosts</dt><dd>${nD(e.allowedHosts)}</dd></div>
4423
4423
  </dl>
4424
4424
  </section>
4425
4425
  `}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
4426
4426
  <section class="effective-card" aria-label="Effective selected machine file access and upload summary">
4427
4427
  <h3>Effective selected-machine settings</h3>
4428
4428
  <dl>
4429
- <div><dt>External roots</dt><dd>${nD(e.pathAccess?.allowedPaths)}</dd></div>
4429
+ <div><dt>External roots</dt><dd>${rD(e.pathAccess?.allowedPaths)}</dd></div>
4430
4430
  <div><dt>Upload folder</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">${`.pi-webui/uploads`} default</span>`}</dd></div>
4431
4431
  </dl>
4432
4432
  </section>
4433
- `}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(GE(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=oD(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(KE(this.machineDraft))}catch(e){this.machineLocalError=oD(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
4433
+ `}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(KE(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=sD(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(qE(this.machineDraft))}catch(e){this.machineLocalError=sD(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
4434
4434
  :host { display: block; }
4435
4435
  .card-heading { display: grid; gap: 6px; min-width: 0; }
4436
4436
  h3, p { margin: 0; }
@@ -4469,10 +4469,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4469
4469
  @media (max-width: 760px) {
4470
4470
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
4471
4471
  }
4472
- `}};B([x({attribute:!1})],eD.prototype,`configResponse`,void 0),B([x({attribute:!1})],eD.prototype,`machineConfigResponse`,void 0),B([x({type:Boolean})],eD.prototype,`loading`,void 0),B([x({type:Boolean})],eD.prototype,`machineLoading`,void 0),B([x({type:Boolean})],eD.prototype,`saving`,void 0),B([x()],eD.prototype,`error`,void 0),B([x()],eD.prototype,`machineError`,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,`onReloadMachine`,void 0),B([x({attribute:!1})],eD.prototype,`onSave`,void 0),B([x({attribute:!1})],eD.prototype,`onSaveMachineConfig`,void 0),B([S()],eD.prototype,`gatewayDraft`,void 0),B([S()],eD.prototype,`machineDraft`,void 0),B([S()],eD.prototype,`gatewayLocalError`,void 0),B([S()],eD.prototype,`machineLocalError`,void 0),eD=B([b(`settings-general-panel`)],eD);function tD(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 nD(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function rD(e){return e.target instanceof HTMLInputElement?e.target.value:``}function iD(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function aD(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function oD(e){return e instanceof Error?e.message:String(e)}function sD(e){return{spawnSessions:e}}function cD(e){return{subsessions:e}}function lD(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`,...Mt(n.command)?[`PI_CODING_AGENT_SESSION_DIR`]:[]];return n.command===t.command&&n.dir===t.dir&&fD(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function uD(e,t){return e?.agentDirSource===`pi-webui`?!0:e?.agentDirSource===`pi-compatibility`?Mt(t.trim()||`pi`):e?.agentDir===!0}function dD(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 fD(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var pD=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=zE(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=zE(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||WE(this.agentDraft,this.configResponse.config))&&(this.agentDraft=HE(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=uD(e?.envOverrides,s),l=e?.envOverrides.agentDir===!0,u=e?.effectiveConfig.agent,d=lD(e,this.activeAgentProfile);return g`
4472
+ `}};B([x({attribute:!1})],tD.prototype,`configResponse`,void 0),B([x({attribute:!1})],tD.prototype,`machineConfigResponse`,void 0),B([x({type:Boolean})],tD.prototype,`loading`,void 0),B([x({type:Boolean})],tD.prototype,`machineLoading`,void 0),B([x({type:Boolean})],tD.prototype,`saving`,void 0),B([x()],tD.prototype,`error`,void 0),B([x()],tD.prototype,`machineError`,void 0),B([x()],tD.prototype,`savedMessage`,void 0),B([x()],tD.prototype,`targetLabel`,void 0),B([x({attribute:!1})],tD.prototype,`onReload`,void 0),B([x({attribute:!1})],tD.prototype,`onReloadMachine`,void 0),B([x({attribute:!1})],tD.prototype,`onSave`,void 0),B([x({attribute:!1})],tD.prototype,`onSaveMachineConfig`,void 0),B([S()],tD.prototype,`gatewayDraft`,void 0),B([S()],tD.prototype,`machineDraft`,void 0),B([S()],tD.prototype,`gatewayLocalError`,void 0),B([S()],tD.prototype,`machineLocalError`,void 0),tD=B([b(`settings-general-panel`)],tD);function nD(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 rD(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function iD(e){return e.target instanceof HTMLInputElement?e.target.value:``}function aD(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function oD(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function sD(e){return e instanceof Error?e.message:String(e)}function cD(e){return{spawnSessions:e}}function lD(e){return{subsessions:e}}function uD(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`,...Mt(n.command)?[`PI_CODING_AGENT_SESSION_DIR`]:[]];return n.command===t.command&&n.dir===t.dir&&pD(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function dD(e,t){return e?.agentDirSource===`pi-webui`?!0:e?.agentDirSource===`pi-compatibility`?Mt(t.trim()||`pi`):e?.agentDir===!0}function fD(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 pD(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var mD=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=BE(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=BE(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||GE(this.agentDraft,this.configResponse.config))&&(this.agentDraft=UE(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=dD(e?.envOverrides,s),l=e?.envOverrides.agentDir===!0,u=e?.effectiveConfig.agent,d=uD(e,this.activeAgentProfile);return g`
4473
4473
  <settings-panel-frame
4474
4474
  heading="Session daemon"
4475
- .description=${_D(this.targetLabel)}
4475
+ .description=${vD(this.targetLabel)}
4476
4476
  actionLabel="Reload"
4477
4477
  .actionDisabled=${this.loading}
4478
4478
  .notices=${this.panelNotices(e)}
@@ -4498,7 +4498,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4498
4498
  .value=${this.agentDraft.command}
4499
4499
  placeholder="pi"
4500
4500
  ?disabled=${this.loading||this.saving||!o||a}
4501
- @input=${e=>{this.updateAgentDraft({command:hD(e)})}}
4501
+ @input=${e=>{this.updateAgentDraft({command:gD(e)})}}
4502
4502
  >
4503
4503
  <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>
4504
4504
  </label>
@@ -4515,7 +4515,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4515
4515
  .value=${this.agentDraft.dir}
4516
4516
  placeholder="~/.pi/agent or ~/agent-profiles/work"
4517
4517
  ?disabled=${this.loading||this.saving||!o||c}
4518
- @input=${e=>{this.updateAgentDraft({dir:hD(e)})}}
4518
+ @input=${e=>{this.updateAgentDraft({dir:gD(e)})}}
4519
4519
  >
4520
4520
  <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>
4521
4521
  </label>
@@ -4563,14 +4563,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4563
4563
  <div><dt>Desired state</dt><dd>${u?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
4564
4564
  <div><dt>Active command</dt><dd>${this.activeAgentProfile?.command??g`<span class="muted">Unavailable</span>`}</dd></div>
4565
4565
  <div><dt>Active state</dt><dd>${this.activeAgentProfile?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
4566
- <div><dt>Profile status</dt><dd>${mD(d)}</dd></div>
4566
+ <div><dt>Profile status</dt><dd>${hD(d)}</dd></div>
4567
4567
  <div><dt>Spawn sessions</dt><dd>${n?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
4568
4568
  <div><dt>Subsessions</dt><dd>${i?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
4569
4569
  </dl>
4570
4570
  </section>
4571
4571
  `}
4572
4572
  </settings-panel-frame>
4573
- `}panelNotices(e){return vD(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?.(UE(this.agentDraft))}catch(e){this.agentLocalError=gD(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?.(sD(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(cD(t))}static{this.styles=h`
4573
+ `}panelNotices(e){return yD(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?.(WE(this.agentDraft))}catch(e){this.agentLocalError=_D(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?.(cD(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(lD(t))}static{this.styles=h`
4574
4574
  :host { display: block; }
4575
4575
  h3 { margin: 0; font-size: 13px; line-height: 1.3; }
4576
4576
  button, input { font: inherit; }
@@ -4616,10 +4616,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4616
4616
  @media (max-width: 760px) {
4617
4617
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
4618
4618
  }
4619
- `}};B([x({attribute:!1})],pD.prototype,`configResponse`,void 0),B([x({type:Boolean})],pD.prototype,`loading`,void 0),B([x({type:Boolean})],pD.prototype,`saving`,void 0),B([x()],pD.prototype,`error`,void 0),B([x()],pD.prototype,`savedMessage`,void 0),B([x()],pD.prototype,`targetLabel`,void 0),B([x({attribute:!1})],pD.prototype,`activeAgentProfile`,void 0),B([x({attribute:!1})],pD.prototype,`agentProfileSupport`,void 0),B([x({attribute:!1})],pD.prototype,`onReload`,void 0),B([x({attribute:!1})],pD.prototype,`onSave`,void 0),B([S()],pD.prototype,`agentDraft`,void 0),B([S()],pD.prototype,`agentDraftDirty`,void 0),B([S()],pD.prototype,`agentLocalError`,void 0),pD=B([b(`settings-sessiond-panel`)],pD);function mD(e){return e===`active`?`Active`:e===`restart-required`?`Restart required`:g`<span class="muted">Unavailable</span>`}function hD(e){return e.target instanceof HTMLInputElement?e.target.value:``}function gD(e){return e instanceof Error?e.message:String(e)}function _D(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 vD(e,t){let n=[];t.error!==``&&n.push({type:`error`,content:t.error}),t.savedMessage!==``&&n.push({type:`success`,content:t.savedMessage});let r=lD(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 yD(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function bD(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function xD(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Kt(t,T.piPackagesManage)?{state:`supported`}:{state:`unsupported`,message:wD(e)}:{state:`unknown`}}function SD(e){return`${e.state}:${e.message??``}`}function CD(e){return e?.state===`unsupported`}function wD(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function TD(e){return e.kind===`local`}function ED(e){return e.trim()}function DD(e){if(ED(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function OD(e){return e.scope===`project`?`Project scope`:`User scope`}function kD(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEBUI process`}function AD(e){return e.installedPath??`Installed path not reported by Pi`}function jD(e){return e.scope===`user`}function MD(e){if(!jD(e))return`Project-scope Pi packages are listed for visibility, but PI WEBUI only updates user-scope Pi packages safely from this view.`}function ND(e){return e.length>0&&e.every(jD)}function PD(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!ND(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function FD(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function ID(e,t=yD(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 LD(e,t){let n=e.trim();return t.kind===`remote`?RD(n)?wD(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 RD(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 zD=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=bD(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
4619
+ `}};B([x({attribute:!1})],mD.prototype,`configResponse`,void 0),B([x({type:Boolean})],mD.prototype,`loading`,void 0),B([x({type:Boolean})],mD.prototype,`saving`,void 0),B([x()],mD.prototype,`error`,void 0),B([x()],mD.prototype,`savedMessage`,void 0),B([x()],mD.prototype,`targetLabel`,void 0),B([x({attribute:!1})],mD.prototype,`activeAgentProfile`,void 0),B([x({attribute:!1})],mD.prototype,`agentProfileSupport`,void 0),B([x({attribute:!1})],mD.prototype,`onReload`,void 0),B([x({attribute:!1})],mD.prototype,`onSave`,void 0),B([S()],mD.prototype,`agentDraft`,void 0),B([S()],mD.prototype,`agentDraftDirty`,void 0),B([S()],mD.prototype,`agentLocalError`,void 0),mD=B([b(`settings-sessiond-panel`)],mD);function hD(e){return e===`active`?`Active`:e===`restart-required`?`Restart required`:g`<span class="muted">Unavailable</span>`}function gD(e){return e.target instanceof HTMLInputElement?e.target.value:``}function _D(e){return e instanceof Error?e.message:String(e)}function vD(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 yD(e,t){let n=[];t.error!==``&&n.push({type:`error`,content:t.error}),t.savedMessage!==``&&n.push({type:`success`,content:t.savedMessage});let r=uD(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 bD(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function xD(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function SD(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Kt(t,T.piPackagesManage)?{state:`supported`}:{state:`unsupported`,message:TD(e)}:{state:`unknown`}}function CD(e){return`${e.state}:${e.message??``}`}function wD(e){return e?.state===`unsupported`}function TD(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function ED(e){return e.kind===`local`}function DD(e){return e.trim()}function OD(e){if(DD(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function kD(e){return e.scope===`project`?`Project scope`:`User scope`}function AD(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEBUI process`}function jD(e){return e.installedPath??`Installed path not reported by Pi`}function MD(e){return e.scope===`user`}function ND(e){if(!MD(e))return`Project-scope Pi packages are listed for visibility, but PI WEBUI only updates user-scope Pi packages safely from this view.`}function PD(e){return e.length>0&&e.every(MD)}function FD(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!PD(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function ID(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function LD(e,t=bD(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 RD(e,t){let n=e.trim();return t.kind===`remote`?zD(n)?TD(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 zD(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 BD=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=xD(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
4620
4620
  <settings-panel-frame
4621
4621
  heading="Pi packages"
4622
- .description=${BD(n)}
4622
+ .description=${VD(n)}
4623
4623
  actionLabel="Reload"
4624
4624
  actionTitle=${r?this.packageManagementUnavailableMessage(n):`Reload Pi packages from ${n}`}
4625
4625
  .actionDisabled=${this.loading||this.isOperating||r}
@@ -4636,12 +4636,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4636
4636
  <label for="package-source">Pi package source</label>
4637
4637
  <div class="install-row">
4638
4638
  <input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package, git URL, or local path" @input=${e=>{this.updateInstallSource(e)}}>
4639
- <button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${FD(this.operation,`install`)?`Installing…`:`Install`}</button>
4639
+ <button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${ID(this.operation,`install`)?`Installing…`:`Install`}</button>
4640
4640
  </div>
4641
4641
  ${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
4642
4642
  <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>
4643
4643
  </form>
4644
- `}renderPackageList(e,t){let n=bD(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):PD(e),i=r!==void 0&&e.length>0;return g`
4644
+ `}renderPackageList(e,t){let n=xD(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):FD(e),i=r!==void 0&&e.length>0;return g`
4645
4645
  <section class="package-section" aria-label="Configured Pi packages">
4646
4646
  <div class="package-toolbar">
4647
4647
  <div>
@@ -4649,7 +4649,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4649
4649
  <p>This list comes from Pi's package manager settings on ${n}.</p>
4650
4650
  </div>
4651
4651
  <button class="secondary" title=${r??`Update all user-scope Pi packages`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
4652
- ${FD(this.operation,`update-all`)?`Updating…`:`Update all`}
4652
+ ${ID(this.operation,`update-all`)?`Updating…`:`Update all`}
4653
4653
  </button>
4654
4654
  </div>
4655
4655
  ${i?g`<div class="action-note">${r}</div>`:null}
@@ -4660,12 +4660,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4660
4660
  <div class="package-list">
4661
4661
  ${e.map(e=>this.renderPackage(e))}
4662
4662
  </div>
4663
- `}renderPackage(e){let t=bD(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):MD(e),i=n?this.packageManagementUnavailableMessage(t):`Remove this Pi package`,a=FD(this.operation,`update`,e.source),o=FD(this.operation,`remove`,e.source);return g`
4663
+ `}renderPackage(e){let t=xD(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):ND(e),i=n?this.packageManagementUnavailableMessage(t):`Remove this Pi package`,a=ID(this.operation,`update`,e.source),o=ID(this.operation,`remove`,e.source);return g`
4664
4664
  <article class=${`package-card${e.filtered?` filtered`:``}`}>
4665
4665
  <div class="package-main">
4666
4666
  <strong>${e.source}</strong>
4667
- <small>${OD(e)} · ${kD(e)}</small>
4668
- <small>Installed path: <code>${AD(e)}</code></small>
4667
+ <small>${kD(e)} · ${AD(e)}</small>
4668
+ <small>Installed path: <code>${jD(e)}</code></small>
4669
4669
  ${r===void 0?null:g`<small class="action-note">${r}</small>`}
4670
4670
  </div>
4671
4671
  <div class="package-actions">
@@ -4673,7 +4673,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4673
4673
  <button class="danger" title=${i} ?disabled=${this.isOperating||n} @click=${()=>{this.removePackage(e)}}>${o?`Removing…`:`Remove`}</button>
4674
4674
  </div>
4675
4675
  </article>
4676
- `}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=DD(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=ED(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??yD(void 0)}get packageManagementUnavailable(){return CD(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`
4676
+ `}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=OD(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=DD(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??bD(void 0)}get packageManagementUnavailable(){return wD(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`
4677
4677
  :host { display: block; }
4678
4678
  .package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
4679
4679
  .package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
@@ -4708,10 +4708,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4708
4708
  .package-actions { justify-self: start; flex-wrap: wrap; }
4709
4709
  .package-main strong, .package-main small { white-space: normal; }
4710
4710
  }
4711
- `}};B([x({attribute:!1})],zD.prototype,`packagesResponse`,void 0),B([x({type:Boolean})],zD.prototype,`loading`,void 0),B([x({attribute:!1})],zD.prototype,`operation`,void 0),B([x({attribute:!1})],zD.prototype,`targetMachine`,void 0),B([x({attribute:!1})],zD.prototype,`managementSupport`,void 0),B([x()],zD.prototype,`error`,void 0),B([x()],zD.prototype,`operationMessage`,void 0),B([x({attribute:!1})],zD.prototype,`onReload`,void 0),B([x({attribute:!1})],zD.prototype,`onInstallPackage`,void 0),B([x({attribute:!1})],zD.prototype,`onRemovePackage`,void 0),B([x({attribute:!1})],zD.prototype,`onUpdatePackage`,void 0),B([S()],zD.prototype,`installSource`,void 0),B([S()],zD.prototype,`validationMessage`,void 0),zD=B([b(`settings-packages-panel`)],zD);function BD(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 VD=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`
4711
+ `}};B([x({attribute:!1})],BD.prototype,`packagesResponse`,void 0),B([x({type:Boolean})],BD.prototype,`loading`,void 0),B([x({attribute:!1})],BD.prototype,`operation`,void 0),B([x({attribute:!1})],BD.prototype,`targetMachine`,void 0),B([x({attribute:!1})],BD.prototype,`managementSupport`,void 0),B([x()],BD.prototype,`error`,void 0),B([x()],BD.prototype,`operationMessage`,void 0),B([x({attribute:!1})],BD.prototype,`onReload`,void 0),B([x({attribute:!1})],BD.prototype,`onInstallPackage`,void 0),B([x({attribute:!1})],BD.prototype,`onRemovePackage`,void 0),B([x({attribute:!1})],BD.prototype,`onUpdatePackage`,void 0),B([S()],BD.prototype,`installSource`,void 0),B([S()],BD.prototype,`validationMessage`,void 0),BD=B([b(`settings-packages-panel`)],BD);function VD(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 HD=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`
4712
4712
  <settings-panel-frame
4713
4713
  heading="PI WEBUI plugins"
4714
- .description=${HD(this.targetLabel)}
4714
+ .description=${UD(this.targetLabel)}
4715
4715
  actionLabel="Reload"
4716
4716
  actionTitle=${`Reload PI WEBUI plugins from ${this.targetLabel}`}
4717
4717
  .actionDisabled=${this.loading}
@@ -4757,7 +4757,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4757
4757
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
4758
4758
  .toggle { justify-self: start; }
4759
4759
  }
4760
- `}};B([x({attribute:!1})],VD.prototype,`pluginsResponse`,void 0),B([x({attribute:!1})],VD.prototype,`configResponse`,void 0),B([x({type:Boolean})],VD.prototype,`loading`,void 0),B([x({type:Boolean})],VD.prototype,`saving`,void 0),B([x()],VD.prototype,`error`,void 0),B([x()],VD.prototype,`savedMessage`,void 0),B([x()],VD.prototype,`targetLabel`,void 0),B([x({attribute:!1})],VD.prototype,`onReload`,void 0),B([x({attribute:!1})],VD.prototype,`onTogglePlugin`,void 0),VD=B([b(`settings-plugins-panel`)],VD);function HD(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.`}function UD(){return{economy:YD(),fast:YD(),standard:YD(),advanced:YD(),capable:YD(),frontier:YD()}}function WD(e){return e.ladder===void 0?UD():{economy:XD(e.ladder.economy),fast:XD(e.ladder.fast),standard:XD(e.ladder.standard),advanced:XD(e.ladder.advanced),capable:XD(e.ladder.capable),frontier:XD(e.ladder.frontier)}}function GD(e,t,n){let r=e[t],i=r.thinkingLevel===``||n.thinkingLevels.includes(r.thinkingLevel)?r.thinkingLevel:``;return{...e,[t]:{model:{...n.model},thinkingLevel:i}}}function KD(e,t,n){return{...e,[t]:{...e[t],thinkingLevel:n}}}function qD(e,t){let n={economy:QD(`economy`,e.economy,t),fast:QD(`fast`,e.fast,t),standard:QD(`standard`,e.standard,t),advanced:QD(`advanced`,e.advanced,t),capable:QD(`capable`,e.capable,t),frontier:QD(`frontier`,e.frontier,t)};return{valid:Et.every(e=>n[e].valid),rows:n}}function JD(e,t){if(qD(e,t).valid)return{economy:ZD(e.economy),fast:ZD(e.fast),standard:ZD(e.standard),advanced:ZD(e.advanced),capable:ZD(e.capable),frontier:ZD(e.frontier)}}function YD(){return{thinkingLevel:``}}function XD(e){return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function ZD(e){if(e.model===void 0)throw Error(`Cannot build a model-tier ladder from an incomplete draft`);return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function QD(e,t,n){let r=t.model;if(r===void 0)return{valid:!1,reason:`tier ${e} has no model selected`};let i=n.find(e=>$D(e.model,r));return i===void 0?{valid:!1,reason:`tier ${e} names unavailable model ${eO(r)}`}:t.thinkingLevel===``?{valid:!1,reason:`tier ${e} has no thinking level selected`}:i.thinkingLevels.includes(t.thinkingLevel)?{valid:!0}:{valid:!1,reason:`tier ${e} names thinking level ${t.thinkingLevel}, unsupported by ${eO(r)}`}}function $D(e,t){return e.provider===t.provider&&e.id===t.id}function eO(e){return`${e.provider}/${e.id}`}var tO={economy:{label:`Economy`,step:`1`},fast:{label:`Fast`,step:`↓`},standard:{label:`Standard`,step:`↓`},advanced:{label:`Advanced`,step:`↓`},capable:{label:`Capable`,step:`↓`},frontier:{label:`Frontier`,step:`6`}},nO=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.support={state:`supported`},this.draft=UD()}get canSave(){let e=this.response?.models??[];return qD(this.draft,e).valid&&!this.saving&&!this.loading&&this.support.state===`supported`}willUpdate(e){e.has(`response`)&&(this.response===void 0?this.draft=UD():this.draft=WD(this.response))}handleReload(){this.onReload?.()}handleSave(){if(!this.canSave)return;let e=this.response?.models??[],t=JD(this.draft,e);t&&this.onSave&&this.onSave(t)}handleModelChange(e,t){this.draft=GD(this.draft,e,t)}handleThinkingChange(e,t){this.draft=KD(this.draft,e,t)}onModelSelectChange(e,t){if(!(t.target instanceof HTMLSelectElement))return;let n=t.target.value,r=(this.response?.models??[]).find(e=>iO(e.model)===n);r!==void 0&&this.handleModelChange(e,r)}onThinkingSelectChange(e,t){t.target instanceof HTMLSelectElement&&this.handleThinkingChange(e,t.target.value)}panelNotices(){let e=[];return this.support.state===`unsupported`?e.push({type:`availability`,tone:`error`,content:this.support.message??`Model tier configuration is not available on ${this.targetLabel}. Update and restart Pi-Web on that machine, then try again.`}):this.support.state===`unknown`&&e.push({type:`availability`,tone:`warning`,content:this.support.message??`Model tier configuration support is unknown for ${this.targetLabel}.`}),this.error!==``&&e.push({type:`error`,content:this.error}),this.response?.configError!==void 0&&this.response.configError!==``&&e.push({type:`error`,title:`Configuration error`,content:this.response.configError}),this.savedMessage!==``&&e.push({type:`success`,content:this.savedMessage}),e}render(){let e=this.response?.models??[],t=qD(this.draft,e),n=Et.filter(e=>t.rows[e].valid).length,r=this.loading||this.saving||this.support.state!==`supported`;return g`
4760
+ `}};B([x({attribute:!1})],HD.prototype,`pluginsResponse`,void 0),B([x({attribute:!1})],HD.prototype,`configResponse`,void 0),B([x({type:Boolean})],HD.prototype,`loading`,void 0),B([x({type:Boolean})],HD.prototype,`saving`,void 0),B([x()],HD.prototype,`error`,void 0),B([x()],HD.prototype,`savedMessage`,void 0),B([x()],HD.prototype,`targetLabel`,void 0),B([x({attribute:!1})],HD.prototype,`onReload`,void 0),B([x({attribute:!1})],HD.prototype,`onTogglePlugin`,void 0),HD=B([b(`settings-plugins-panel`)],HD);function UD(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.`}function WD(){return{economy:XD(),fast:XD(),standard:XD(),advanced:XD(),capable:XD(),frontier:XD()}}function GD(e){return e.ladder===void 0?WD():{economy:ZD(e.ladder.economy),fast:ZD(e.ladder.fast),standard:ZD(e.ladder.standard),advanced:ZD(e.ladder.advanced),capable:ZD(e.ladder.capable),frontier:ZD(e.ladder.frontier)}}function KD(e,t,n){let r=e[t],i=r.thinkingLevel===``||n.thinkingLevels.includes(r.thinkingLevel)?r.thinkingLevel:``;return{...e,[t]:{model:{...n.model},thinkingLevel:i}}}function qD(e,t,n){return{...e,[t]:{...e[t],thinkingLevel:n}}}function JD(e,t){let n={economy:$D(`economy`,e.economy,t),fast:$D(`fast`,e.fast,t),standard:$D(`standard`,e.standard,t),advanced:$D(`advanced`,e.advanced,t),capable:$D(`capable`,e.capable,t),frontier:$D(`frontier`,e.frontier,t)};return{valid:Et.every(e=>n[e].valid),rows:n}}function YD(e,t){if(JD(e,t).valid)return{economy:QD(e.economy),fast:QD(e.fast),standard:QD(e.standard),advanced:QD(e.advanced),capable:QD(e.capable),frontier:QD(e.frontier)}}function XD(){return{thinkingLevel:``}}function ZD(e){return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function QD(e){if(e.model===void 0)throw Error(`Cannot build a model-tier ladder from an incomplete draft`);return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function $D(e,t,n){let r=t.model;if(r===void 0)return{valid:!1,reason:`tier ${e} has no model selected`};let i=n.find(e=>eO(e.model,r));return i===void 0?{valid:!1,reason:`tier ${e} names unavailable model ${tO(r)}`}:t.thinkingLevel===``?{valid:!1,reason:`tier ${e} has no thinking level selected`}:i.thinkingLevels.includes(t.thinkingLevel)?{valid:!0}:{valid:!1,reason:`tier ${e} names thinking level ${t.thinkingLevel}, unsupported by ${tO(r)}`}}function eO(e,t){return e.provider===t.provider&&e.id===t.id}function tO(e){return`${e.provider}/${e.id}`}var nO={economy:{label:`Economy`,step:`1`},fast:{label:`Fast`,step:`↓`},standard:{label:`Standard`,step:`↓`},advanced:{label:`Advanced`,step:`↓`},capable:{label:`Capable`,step:`↓`},frontier:{label:`Frontier`,step:`6`}},rO=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.support={state:`supported`},this.draft=WD()}get canSave(){let e=this.response?.models??[];return JD(this.draft,e).valid&&!this.saving&&!this.loading&&this.support.state===`supported`}willUpdate(e){e.has(`response`)&&(this.response===void 0?this.draft=WD():this.draft=GD(this.response))}handleReload(){this.onReload?.()}handleSave(){if(!this.canSave)return;let e=this.response?.models??[],t=YD(this.draft,e);t&&this.onSave&&this.onSave(t)}handleModelChange(e,t){this.draft=KD(this.draft,e,t)}handleThinkingChange(e,t){this.draft=qD(this.draft,e,t)}onModelSelectChange(e,t){if(!(t.target instanceof HTMLSelectElement))return;let n=t.target.value,r=(this.response?.models??[]).find(e=>aO(e.model)===n);r!==void 0&&this.handleModelChange(e,r)}onThinkingSelectChange(e,t){t.target instanceof HTMLSelectElement&&this.handleThinkingChange(e,t.target.value)}panelNotices(){let e=[];return this.support.state===`unsupported`?e.push({type:`availability`,tone:`error`,content:this.support.message??`Model tier configuration is not available on ${this.targetLabel}. Update and restart Pi-Web on that machine, then try again.`}):this.support.state===`unknown`&&e.push({type:`availability`,tone:`warning`,content:this.support.message??`Model tier configuration support is unknown for ${this.targetLabel}.`}),this.error!==``&&e.push({type:`error`,content:this.error}),this.response?.configError!==void 0&&this.response.configError!==``&&e.push({type:`error`,title:`Configuration error`,content:this.response.configError}),this.savedMessage!==``&&e.push({type:`success`,content:this.savedMessage}),e}render(){let e=this.response?.models??[],t=JD(this.draft,e),n=Et.filter(e=>t.rows[e].valid).length,r=this.loading||this.saving||this.support.state!==`supported`;return g`
4761
4761
  <settings-panel-frame
4762
4762
  heading="Model tiers"
4763
4763
  description="Configure the six exact model/thinking bindings used by tiered sessions."
@@ -4791,7 +4791,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4791
4791
  </footer>
4792
4792
  `}
4793
4793
  </settings-panel-frame>
4794
- `}renderTierRow(e,t,n,r){let i=tO[e],a=this.draft[e],o=n.rows[e],s=a.model,c=s!==void 0&&t.some(e=>rO(e.model,s)),l=s?t.find(e=>rO(e.model,s)):void 0;return g`
4794
+ `}renderTierRow(e,t,n,r){let i=nO[e],a=this.draft[e],o=n.rows[e],s=a.model,c=s!==void 0&&t.some(e=>iO(e.model,s)),l=s?t.find(e=>iO(e.model,s)):void 0;return g`
4795
4795
  <div class="tier-row ${o.valid?``:`invalid`}" data-tier=${e}>
4796
4796
  <div class="step-col" aria-hidden="true">${i.step}</div>
4797
4797
  <div class="tier-col">
@@ -4804,15 +4804,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4804
4804
  id=${`select-model-${e}`}
4805
4805
  aria-invalid=${String(!o.valid)}
4806
4806
  ?disabled=${r}
4807
- .value=${s?iO(s):``}
4807
+ .value=${s?aO(s):``}
4808
4808
  @change=${t=>{this.onModelSelectChange(e,t)}}
4809
- title=${s?aO(s):`Select model`}
4809
+ title=${s?oO(s):`Select model`}
4810
4810
  >
4811
4811
  ${s===void 0?g`<option value="" disabled ?selected=${!0}>Select a model…</option>`:null}
4812
- ${s!==void 0&&!c?g`<option value=${iO(s)} disabled selected>
4813
- ${aO(s)} (unavailable)
4812
+ ${s!==void 0&&!c?g`<option value=${aO(s)} disabled selected>
4813
+ ${oO(s)} (unavailable)
4814
4814
  </option>`:null}
4815
- ${t.map(e=>{let t=s!==void 0&&rO(e.model,s),n=e.name!==void 0&&e.name!==``?`${e.name} (${aO(e.model)})`:aO(e.model);return g`<option value=${iO(e.model)} ?selected=${t}>${n}</option>`})}
4815
+ ${t.map(e=>{let t=s!==void 0&&iO(e.model,s),n=e.name!==void 0&&e.name!==``?`${e.name} (${oO(e.model)})`:oO(e.model);return g`<option value=${aO(e.model)} ?selected=${t}>${n}</option>`})}
4816
4816
  </select>
4817
4817
  </div>
4818
4818
 
@@ -5008,10 +5008,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5008
5008
  width: 100%;
5009
5009
  }
5010
5010
  }
5011
- `}};B([x({attribute:!1})],nO.prototype,`response`,void 0),B([x({type:Boolean})],nO.prototype,`loading`,void 0),B([x({type:Boolean})],nO.prototype,`saving`,void 0),B([x()],nO.prototype,`error`,void 0),B([x()],nO.prototype,`savedMessage`,void 0),B([x()],nO.prototype,`targetLabel`,void 0),B([x({attribute:!1})],nO.prototype,`support`,void 0),B([x({attribute:!1})],nO.prototype,`onReload`,void 0),B([x({attribute:!1})],nO.prototype,`onSave`,void 0),B([S()],nO.prototype,`draft`,void 0),nO=B([b(`settings-model-tiers-panel`)],nO);function rO(e,t){return e.provider===t.provider&&e.id===t.id}function iO(e){return`${e.provider}:${e.id}`}function aO(e){return`${e.provider}/${e.id}`}var oO={capture:!0},sO=[{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 cO(){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 lO=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=lw(),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=ep(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&&!tp(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=pO(this.actions),t=this.shortcutResolutions();return g`
5011
+ `}};B([x({attribute:!1})],rO.prototype,`response`,void 0),B([x({type:Boolean})],rO.prototype,`loading`,void 0),B([x({type:Boolean})],rO.prototype,`saving`,void 0),B([x()],rO.prototype,`error`,void 0),B([x()],rO.prototype,`savedMessage`,void 0),B([x()],rO.prototype,`targetLabel`,void 0),B([x({attribute:!1})],rO.prototype,`support`,void 0),B([x({attribute:!1})],rO.prototype,`onReload`,void 0),B([x({attribute:!1})],rO.prototype,`onSave`,void 0),B([S()],rO.prototype,`draft`,void 0),rO=B([b(`settings-model-tiers-panel`)],rO);function iO(e,t){return e.provider===t.provider&&e.id===t.id}function aO(e){return`${e.provider}:${e.id}`}function oO(e){return`${e.provider}/${e.id}`}var sO={capture:!0},cO=[{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 lO(){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 uO=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=uw(),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=ep(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&&!tp(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=mO(this.actions),t=this.shortcutResolutions();return g`
5012
5012
  <settings-panel-frame
5013
5013
  heading="Keyboard shortcuts"
5014
- .description=${cO()}
5014
+ .description=${lO()}
5015
5015
  actionLabel="Reload"
5016
5016
  .actionDisabled=${this.loading}
5017
5017
  .notices=${this.panelNotices()}
@@ -5042,7 +5042,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5042
5042
  <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>
5043
5043
  </div>
5044
5044
  <div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
5045
- ${sO.map(e=>g`
5045
+ ${cO.map(e=>g`
5046
5046
  <label class="prompt-enter-option">
5047
5047
  <input
5048
5048
  type="radio"
@@ -5059,8 +5059,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5059
5059
  `)}
5060
5060
  </div>
5061
5061
  </section>
5062
- `}updatePromptEnterPreference(e){this.promptEnterPreference=e,uw(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=hO(e.id,n),i=vO(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Zf(a),s=o?.ok===!0?o.shortcut:_O(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=fO(t);return g`
5063
- <article class=${uO(t)}>
5062
+ `}updatePromptEnterPreference(e){this.promptEnterPreference=e,dw(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=gO(e.id,n),i=yO(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Zf(a),s=o?.ok===!0?o.shortcut:vO(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=pO(t);return g`
5063
+ <article class=${dO(t)}>
5064
5064
  <div class="shortcut-main">
5065
5065
  <strong>${e.title}</strong>
5066
5066
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
@@ -5070,8 +5070,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5070
5070
  <div class="shortcut-editor">
5071
5071
  <div class="shortcut-status">
5072
5072
  ${s!==void 0&&s!==``?g`<kbd>${$f(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`Disabled`:`Unassigned`}</span>`}
5073
- <small class=${u}>${yO(u)}${l?` · Unsaved`:``}</small>
5074
- ${f===void 0?null:g`<small class=${dO(t)}>${f}</small>`}
5073
+ <small class=${u}>${bO(u)}${l?` · Unsaved`:``}</small>
5074
+ ${f===void 0?null:g`<small class=${fO(t)}>${f}</small>`}
5075
5075
  </div>
5076
5076
  <label class="shortcut-input-label">
5077
5077
  <span>Shortcut</span>
@@ -5084,7 +5084,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5084
5084
  autocapitalize="off"
5085
5085
  spellcheck="false"
5086
5086
  ?disabled=${this.saving}
5087
- @input=${t=>{this.updateDraft(e.id,bO(t))}}
5087
+ @input=${t=>{this.updateDraft(e.id,xO(t))}}
5088
5088
  >
5089
5089
  </label>
5090
5090
  ${d===``?null:g`<small class="recording-hint">${d}</small>`}
@@ -5096,7 +5096,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5096
5096
  </div>
5097
5097
  </div>
5098
5098
  </article>
5099
- `}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=hO(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: ${$f(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=Zf(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?gO(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Xf(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=Zf(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()},qf)}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,oO),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,oO),!1)}static{this.styles=h`
5099
+ `}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=gO(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: ${$f(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=Zf(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?_O(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Xf(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=Zf(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()},qf)}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,sO),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,sO),!1)}static{this.styles=h`
5100
5100
  :host { display: block; }
5101
5101
  h3, p { margin: 0; }
5102
5102
  h3 { font-size: 13px; line-height: 1.3; }
@@ -5152,7 +5152,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5152
5152
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
5153
5153
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
5154
5154
  }
5155
- `}};B([x({attribute:!1})],lO.prototype,`actions`,void 0),B([x({attribute:!1})],lO.prototype,`configResponse`,void 0),B([x({type:Boolean})],lO.prototype,`loading`,void 0),B([x({type:Boolean})],lO.prototype,`saving`,void 0),B([x()],lO.prototype,`error`,void 0),B([x()],lO.prototype,`savedMessage`,void 0),B([x({attribute:!1})],lO.prototype,`onReload`,void 0),B([x({attribute:!1})],lO.prototype,`onSave`,void 0),B([S()],lO.prototype,`drafts`,void 0),B([S()],lO.prototype,`localError`,void 0),B([S()],lO.prototype,`promptEnterPreference`,void 0),B([S()],lO.prototype,`recording`,void 0),lO=B([b(`settings-shortcuts-panel`)],lO);function uO(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function dO(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function fO(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 pO(e){let t=new Map;for(let n of[...e].sort(mO)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function mO(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function hO(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function gO(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function _O(e,t){let n=hO(e.id,t);if(n!==null)return n??e.shortcut}function vO(e,t){let n=hO(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function yO(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function bO(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function xO(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: ${CO(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEBUI plugins: ${CO(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function SO(e,t,n){if(CD(n))return{error:n.message??`Pi package management is not available on ${bD(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${bD(e)}: ${LD(CO(t),e)}`}}}function CO(e){return e instanceof Error?e.message:String(e)}function wO(e,t){return{...e,config:TO(e.config,t.config),effectiveConfig:TO(e.effectiveConfig,t.effectiveConfig)}}function TO(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 EO(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function Y(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function DO(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Kt(t,T.selectedMachineSettings)?{state:`supported`}:{state:`unsupported`,message:NO(e)}:{state:`unknown`}}function OO(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Kt(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 kO(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Kt(t,T.modelTierSettings)?{state:`supported`}:{state:`unsupported`,message:NO(e)}:{state:`unknown`}}function AO(e){return`${e.state}:${e.message??``}`}function jO(e){return e?.state===`unsupported`}function MO(e){return e?.state===`supported`}function NO(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}function PO(e,t){let n=e.trim();return t.kind===`remote`?FO(n)?NO(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 FO(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 IO(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function LO(e,t){return{...e,config:RO(e.config,t.config),effectiveConfig:RO(e.effectiveConfig,t.effectiveConfig)}}function RO(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.modelTiersLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.modelTiersError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0,this.modelTiersLoadRequestSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget(),this.loadModelTiersForTarget()}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`)&&EO(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),this.resetModelTiersStateForTargetChange(),this.isConnected&&this.loadModelTiersForTarget(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.resetModelTiersStateForTargetChange(),this.isConnected&&this.loadModelTiersForTarget(t)),this.packageManagementSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return g`
5155
+ `}};B([x({attribute:!1})],uO.prototype,`actions`,void 0),B([x({attribute:!1})],uO.prototype,`configResponse`,void 0),B([x({type:Boolean})],uO.prototype,`loading`,void 0),B([x({type:Boolean})],uO.prototype,`saving`,void 0),B([x()],uO.prototype,`error`,void 0),B([x()],uO.prototype,`savedMessage`,void 0),B([x({attribute:!1})],uO.prototype,`onReload`,void 0),B([x({attribute:!1})],uO.prototype,`onSave`,void 0),B([S()],uO.prototype,`drafts`,void 0),B([S()],uO.prototype,`localError`,void 0),B([S()],uO.prototype,`promptEnterPreference`,void 0),B([S()],uO.prototype,`recording`,void 0),uO=B([b(`settings-shortcuts-panel`)],uO);function dO(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function fO(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function pO(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 mO(e){let t=new Map;for(let n of[...e].sort(hO)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function hO(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function gO(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function _O(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function vO(e,t){let n=gO(e.id,t);if(n!==null)return n??e.shortcut}function yO(e,t){let n=gO(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function bO(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function xO(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function SO(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: ${wO(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEBUI plugins: ${wO(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function CO(e,t,n){if(wD(n))return{error:n.message??`Pi package management is not available on ${xD(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${xD(e)}: ${RD(wO(t),e)}`}}}function wO(e){return e instanceof Error?e.message:String(e)}function TO(e,t){return{...e,config:EO(e.config,t.config),effectiveConfig:EO(e.effectiveConfig,t.effectiveConfig)}}function EO(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 DO(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function Y(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function OO(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Kt(t,T.selectedMachineSettings)?{state:`supported`}:{state:`unsupported`,message:PO(e)}:{state:`unknown`}}function kO(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Kt(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 AO(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Kt(t,T.modelTierSettings)?{state:`supported`}:{state:`unsupported`,message:PO(e)}:{state:`unknown`}}function jO(e){return`${e.state}:${e.message??``}`}function MO(e){return e?.state===`unsupported`}function NO(e){return e?.state===`supported`}function PO(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}function FO(e,t){let n=e.trim();return t.kind===`remote`?IO(n)?PO(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 IO(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 LO(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function RO(e,t){return{...e,config:zO(e.config,t.config),effectiveConfig:zO(e.effectiveConfig,t.effectiveConfig)}}function zO(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.modelTiersLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.modelTiersError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0,this.modelTiersLoadRequestSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget(),this.loadModelTiersForTarget()}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`)&&DO(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),this.resetModelTiersStateForTargetChange(),this.isConnected&&this.loadModelTiersForTarget(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.resetModelTiersStateForTargetChange(),this.isConnected&&this.loadModelTiersForTarget(t)),this.packageManagementSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return g`
5156
5156
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
5157
5157
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEBUI settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
5158
5158
  <header class="settings-header">
@@ -5260,7 +5260,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5260
5260
  <strong>${t}</strong>
5261
5261
  <small>${n}</small>
5262
5262
  </button>
5263
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await xO({loadConfig:()=>io.config(),loadPlugins:()=>ao.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(jO(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await io.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 ${Y(e)}: ${PO(zO(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(jO(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await io.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 ${Y(e)}: ${PO(zO(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(jO(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([io.config(e.id),ao.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${PO(zO(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${PO(zO(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${Y(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 SO(e,e=>ho.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 loadModelTiersForTarget(e=this.settingsTarget()){let t=++this.modelTiersLoadRequestSeq,n=this.modelTierSettingsSupport(e);if(jO(n)){this.modelTiersConfigResponse=void 0,this.modelTiersLoading=!1,this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.modelTiersLoading=!0,this.modelTiersError=``;try{let n=await lo.settings(e.id);if(!this.isCurrentModelTiersLoad(t,e))return;this.modelTiersConfigResponse=n}catch(n){this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersError=`Failed to load model tier settings from ${Y(e)}: ${PO(zO(n),e)}`)}finally{this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(jO(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${Y(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${Y(n)}. Reload before changing plugin enablement.`;return}let i=IO(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await io.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=LO(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 ${Y(n)}: ${PO(zO(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await io.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${zO(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(jO(n)){this.accessError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await io.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=wO(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 ${Y(t)}: ${PO(zO(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(jO(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!MO(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${Y(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await io.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=dD(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${Y(t)}: ${PO(zO(e),t)}`)}finally{this.saving=!1}}async saveModelTiers(e){if(this.saving)return;let t=this.settingsTarget(),n=this.modelTierSettingsSupport(t);if(jO(n)){this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.modelTiersError=``,this.savedMessage=``;try{let n=await lo.save(e,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.modelTiersConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&n.ladder!==void 0){let e=n.ladder;this.configResponse={...this.configResponse,config:{...this.configResponse.config,modelTiers:e},effectiveConfig:{...this.configResponse.effectiveConfig,modelTiers:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.modelTiersError=`Failed to save model tier settings on ${Y(t)}: ${PO(zO(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>ho.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>ho.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,()=>ho.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(CD(i))throw this.packageError=i.message??`Pi package management is not available on ${bD(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=TD(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=ID(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${bD(n)}: ${LD(zO(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await ao.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${zO(e)}`}}async refreshPluginsForTarget(e){try{let t=await ao.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${Y(e)}: ${PO(zO(t),e)}`}}settingsTarget(){return EO(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return DO(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return OO(e,this.machineRuntime)}modelTierSettingsSupport(e=this.settingsTarget()){return kO(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=DO(t,e),r=this.selectedMachineSettingsSupport(t);return AO(n)!==AO(r)}packageManagementSupport(e=this.packageTarget()){return xD(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=xD(t,e),r=this.packageManagementSupport(t);return SD(n)===SD(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)}isCurrentModelTiersLoad(e,t){return e===this.modelTiersLoadRequestSeq&&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)}resetModelTiersStateForTargetChange(){this.modelTiersLoadRequestSeq+=1,this.modelTiersLoading=!1,this.modelTiersError=``,this.modelTiersConfigResponse=void 0,this.savedMessage=``}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`
5263
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await SO({loadConfig:()=>io.config(),loadPlugins:()=>ao.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(MO(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await io.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 ${Y(e)}: ${FO(BO(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(MO(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await io.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 ${Y(e)}: ${FO(BO(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(MO(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([io.config(e.id),ao.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${FO(BO(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${FO(BO(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${Y(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 CO(e,e=>ho.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 loadModelTiersForTarget(e=this.settingsTarget()){let t=++this.modelTiersLoadRequestSeq,n=this.modelTierSettingsSupport(e);if(MO(n)){this.modelTiersConfigResponse=void 0,this.modelTiersLoading=!1,this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.modelTiersLoading=!0,this.modelTiersError=``;try{let n=await lo.settings(e.id);if(!this.isCurrentModelTiersLoad(t,e))return;this.modelTiersConfigResponse=n}catch(n){this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersError=`Failed to load model tier settings from ${Y(e)}: ${FO(BO(n),e)}`)}finally{this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(MO(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${Y(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${Y(n)}. Reload before changing plugin enablement.`;return}let i=LO(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await io.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=RO(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 ${Y(n)}: ${FO(BO(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await io.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${BO(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(MO(n)){this.accessError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await io.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=TO(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 ${Y(t)}: ${FO(BO(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(MO(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!NO(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${Y(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await io.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=fD(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${Y(t)}: ${FO(BO(e),t)}`)}finally{this.saving=!1}}async saveModelTiers(e){if(this.saving)return;let t=this.settingsTarget(),n=this.modelTierSettingsSupport(t);if(MO(n)){this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.modelTiersError=``,this.savedMessage=``;try{let n=await lo.save(e,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.modelTiersConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&n.ladder!==void 0){let e=n.ladder;this.configResponse={...this.configResponse,config:{...this.configResponse.config,modelTiers:e},effectiveConfig:{...this.configResponse.effectiveConfig,modelTiers:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.modelTiersError=`Failed to save model tier settings on ${Y(t)}: ${FO(BO(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>ho.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>ho.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,()=>ho.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(wD(i))throw this.packageError=i.message??`Pi package management is not available on ${xD(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=ED(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=LD(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${xD(n)}: ${RD(BO(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await ao.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${BO(e)}`}}async refreshPluginsForTarget(e){try{let t=await ao.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${Y(e)}: ${FO(BO(t),e)}`}}settingsTarget(){return DO(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return OO(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return kO(e,this.machineRuntime)}modelTierSettingsSupport(e=this.settingsTarget()){return AO(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=OO(t,e),r=this.selectedMachineSettingsSupport(t);return jO(n)!==jO(r)}packageManagementSupport(e=this.packageTarget()){return SD(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=SD(t,e),r=this.packageManagementSupport(t);return CD(n)===CD(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)}isCurrentModelTiersLoad(e,t){return e===this.modelTiersLoadRequestSeq&&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)}resetModelTiersStateForTargetChange(){this.modelTiersLoadRequestSeq+=1,this.modelTiersLoading=!1,this.modelTiersError=``,this.modelTiersConfigResponse=void 0,this.savedMessage=``}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`
5264
5264
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
5265
5265
  .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; }
5266
5266
  .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; }
@@ -5287,7 +5287,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5287
5287
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
5288
5288
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
5289
5289
  }
5290
- `}};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,`modelTiersConfigResponse`,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,`modelTiersLoading`,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,`modelTiersError`,void 0),B([S()],X.prototype,`savedMessage`,void 0),B([S()],X.prototype,`packageMessage`,void 0),X=B([b(`settings-dialog`)],X);function zO(e){return e instanceof Error?e.message:String(e)}var BO=class extends y{constructor(...e){super(...e),this.sessionsApi=So,this.loading=!0,this.error=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSystemPrompt()}updated(e){let t=e.has(`session`)&&HO(e.get(`session`))!==HO(this.session),n=e.has(`machine`)&&VO(e.get(`machine`))!==VO(this.machine);(t||n)&&this.isConnected&&this.loadSystemPrompt()}render(){return g`
5290
+ `}};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,`modelTiersConfigResponse`,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,`modelTiersLoading`,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,`modelTiersError`,void 0),B([S()],X.prototype,`savedMessage`,void 0),B([S()],X.prototype,`packageMessage`,void 0),X=B([b(`settings-dialog`)],X);function BO(e){return e instanceof Error?e.message:String(e)}var VO=class extends y{constructor(...e){super(...e),this.sessionsApi=So,this.loading=!0,this.error=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSystemPrompt()}updated(e){let t=e.has(`session`)&&UO(e.get(`session`))!==UO(this.session),n=e.has(`machine`)&&HO(e.get(`machine`))!==HO(this.machine);(t||n)&&this.isConnected&&this.loadSystemPrompt()}render(){return g`
5291
5291
  <div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
5292
5292
  <section class="dialog" role="dialog" aria-modal="true" aria-labelledby="system-prompt-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
5293
5293
  <header>
@@ -5296,7 +5296,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5296
5296
  <h1 id="system-prompt-dialog-title">System prompt</h1>
5297
5297
  </div>
5298
5298
  <button class="icon-button" type="button" title="Close system prompt" aria-label="Close system prompt" @click=${()=>{this.close()}}>
5299
- ${KO()}
5299
+ ${qO()}
5300
5300
  </button>
5301
5301
  </header>
5302
5302
  <div class="prompt-body" aria-live="polite">
@@ -5307,7 +5307,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5307
5307
  </footer>
5308
5308
  </section>
5309
5309
  </div>
5310
- `}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:WO(VO(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,VO(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: ${GO(e)}`}finally{this.isCurrentLoad(n,t)&&(this.loading=!1)}}isCurrentLoad(e,t){let n=this.session;return e===this.loadRequestSequence&&n!==void 0&&WO(VO(this.machine),n)===t}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}static{this.styles=h`
5310
+ `}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:GO(HO(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,HO(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: ${KO(e)}`}finally{this.isCurrentLoad(n,t)&&(this.loading=!1)}}isCurrentLoad(e,t){let n=this.session;return e===this.loadRequestSequence&&n!==void 0&&GO(HO(this.machine),n)===t}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}static{this.styles=h`
5311
5311
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
5312
5312
  * { box-sizing: border-box; }
5313
5313
  .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; }
@@ -5333,11 +5333,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5333
5333
  header, footer { padding: 12px; }
5334
5334
  .system-prompt, .prompt-state { padding: 12px; }
5335
5335
  }
5336
- `}};B([x({attribute:!1})],BO.prototype,`machine`,void 0),B([x({attribute:!1})],BO.prototype,`session`,void 0),B([x({attribute:!1})],BO.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],BO.prototype,`onClose`,void 0),B([S()],BO.prototype,`systemPrompt`,void 0),B([S()],BO.prototype,`loading`,void 0),B([S()],BO.prototype,`error`,void 0),BO=B([b(`system-prompt-dialog`)],BO);function VO(e){return e?.id??`local`}function HO(e){return e===void 0?void 0:UO(e)}function UO(e){return JSON.stringify([e.id,e.cwd])}function WO(e,t){return JSON.stringify([e,t.id,t.cwd])}function GO(e){return e instanceof Error?e.message:String(e)}function KO(){return _`
5336
+ `}};B([x({attribute:!1})],VO.prototype,`machine`,void 0),B([x({attribute:!1})],VO.prototype,`session`,void 0),B([x({attribute:!1})],VO.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],VO.prototype,`onClose`,void 0),B([S()],VO.prototype,`systemPrompt`,void 0),B([S()],VO.prototype,`loading`,void 0),B([S()],VO.prototype,`error`,void 0),VO=B([b(`system-prompt-dialog`)],VO);function HO(e){return e?.id??`local`}function UO(e){return e===void 0?void 0:WO(e)}function WO(e){return JSON.stringify([e.id,e.cwd])}function GO(e,t){return JSON.stringify([e,t.id,t.cwd])}function KO(e){return e instanceof Error?e.message:String(e)}function qO(){return _`
5337
5337
  <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
5338
5338
  <path d="M6 6l12 12M18 6 6 18"></path>
5339
5339
  </svg>
5340
- `}var qO=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`
5340
+ `}var JO=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`
5341
5341
  ${this.hideToolTabs?null:g`
5342
5342
  <header>
5343
5343
  <div class=${this.workspaceHeaderFrameClass()}>
@@ -5367,10 +5367,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5367
5367
  <h2>${e.title}</h2>
5368
5368
  ${e.body===void 0?null:g`<p>${e.body}</p>`}
5369
5369
  </section>
5370
- `}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=zm}};B([x({attribute:!1})],qO.prototype,`workspace`,void 0),B([x({attribute:!1})],qO.prototype,`panelContext`,void 0),B([x({attribute:!1})],qO.prototype,`emptyState`,void 0),B([x()],qO.prototype,`tool`,void 0),B([x({attribute:!1})],qO.prototype,`panels`,void 0),B([x({attribute:!1})],qO.prototype,`hiddenTools`,void 0),B([x({type:Boolean})],qO.prototype,`hideToolTabs`,void 0),B([x({attribute:!1})],qO.prototype,`onSelectTool`,void 0),B([C(`.workspace-header-strip`)],qO.prototype,`workspaceHeaderStrip`,void 0),B([S()],qO.prototype,`workspaceHeaderCanScrollLeft`,void 0),B([S()],qO.prototype,`workspaceHeaderCanScrollRight`,void 0),qO=B([b(`workspace-panel`)],qO);var JO=`important`,YO=` !important`,XO=Ov(class extends kv{constructor(e){if(super(e),e.type!==Dv.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(YO);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?JO:``):n[e]=r}}return Qe}}),ZO=`#ffffff`,QO=`#000000`,$O=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],ek=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],tk={black:$O[0],red:$O[1],green:$O[2],yellow:$O[3],blue:$O[4],magenta:$O[5],cyan:$O[6],white:$O[7],brightBlack:$O[8],brightRed:$O[9],brightGreen:$O[10],brightYellow:$O[11],brightBlue:$O[12],brightMagenta:$O[13],brightCyan:$O[14],brightWhite:$O[15]};function nk(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=uk(n.theme),a=n.theme?.foreground??ZO,o=n.theme?.background??QO,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=rk(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,sk(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(`
5371
- `),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function rk(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:ok(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:ik(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,ck(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function ik(e,t){let n=e.isInverse()!==0,r=ak(e,`foreground`,t),i=ak(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 ak(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?dk(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function ok(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function sk(e,t){for(let n of t)ck(e,n)}function ck(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&lk(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function lk(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 uk(e){let t=[...$O];for(let n=0;n<ek.length;n+=1){let r=ek[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(fk(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(fk(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 dk(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function fk(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var pk=`pi-webui.terminal.softKeys`,mk=`(pointer: coarse), (max-width: 760px)`;function hk(e,t){return e??t}function gk(e){if(e===`true`)return!0;if(e===`false`)return!1}function _k(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(mk):void 0}function vk(e){return e?.matches===!0}function yk(e=_k()){return hk(xk(),vk(e))}function bk(){return xk()!==void 0}function xk(e=Ck()){if(e!==void 0)try{return gk(e.getItem(pk))}catch{return}}function Sk(e,t=Ck()){if(t!==void 0)try{t.setItem(pk,String(e))}catch{}}function Ck(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var wk=[{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`}],Tk=`\x1B`,Ek=``;function Dk(e,t){switch(e){case`escape`:return Tk;case`tab`:return` `;case`ctrl-c`:return Ok(`c`);case`ctrl-d`:return Ok(`d`);case`ctrl-z`:return Ok(`z`);case`ctrl-l`:return Ok(`l`);case`ctrl-r`:return Ok(`r`);case`ctrl-u`:return Ok(`u`);case`ctrl-w`:return Ok(`w`);case`arrow-left`:return kk(`D`,t);case`arrow-up`:return kk(`A`,t);case`arrow-down`:return kk(`B`,t);case`arrow-right`:return kk(`C`,t);case`home`:return Ak(`H`,t);case`end`:return Ak(`F`,t);case`page-up`:return`${Tk}[5~`;case`page-down`:return`${Tk}[6~`;case`delete`:return`${Tk}[3~`;case`backspace`:return Ek;case`meta-backward-word`:return`${Tk}b`;case`meta-forward-word`:return`${Tk}f`}}function Ok(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function kk(e,t){return t?.applicationCursorKeysMode===!0?`${Tk}O${e}`:`${Tk}[${e}`}function Ak(e,t){return t?.applicationCursorKeysMode===!0?`${Tk}O${e}`:`${Tk}[${e}`}var jk=8,Mk=500,Nk=class extends y{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(Dk(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&&Pk(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||Pk(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<Mk){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return g`
5370
+ `}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=zm}};B([x({attribute:!1})],JO.prototype,`workspace`,void 0),B([x({attribute:!1})],JO.prototype,`panelContext`,void 0),B([x({attribute:!1})],JO.prototype,`emptyState`,void 0),B([x()],JO.prototype,`tool`,void 0),B([x({attribute:!1})],JO.prototype,`panels`,void 0),B([x({attribute:!1})],JO.prototype,`hiddenTools`,void 0),B([x({type:Boolean})],JO.prototype,`hideToolTabs`,void 0),B([x({attribute:!1})],JO.prototype,`onSelectTool`,void 0),B([C(`.workspace-header-strip`)],JO.prototype,`workspaceHeaderStrip`,void 0),B([S()],JO.prototype,`workspaceHeaderCanScrollLeft`,void 0),B([S()],JO.prototype,`workspaceHeaderCanScrollRight`,void 0),JO=B([b(`workspace-panel`)],JO);var YO=`important`,XO=` !important`,ZO=Ov(class extends kv{constructor(e){if(super(e),e.type!==Dv.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(XO);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?YO:``):n[e]=r}}return Qe}}),QO=`#ffffff`,$O=`#000000`,ek=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],tk=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],nk={black:ek[0],red:ek[1],green:ek[2],yellow:ek[3],blue:ek[4],magenta:ek[5],cyan:ek[6],white:ek[7],brightBlack:ek[8],brightRed:ek[9],brightGreen:ek[10],brightYellow:ek[11],brightBlue:ek[12],brightMagenta:ek[13],brightCyan:ek[14],brightWhite:ek[15]};function rk(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=dk(n.theme),a=n.theme?.foreground??QO,o=n.theme?.background??$O,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=ik(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,ck(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(`
5371
+ `),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function ik(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:sk(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:ak(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,lk(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function ak(e,t){let n=e.isInverse()!==0,r=ok(e,`foreground`,t),i=ok(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 ok(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?fk(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function sk(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function ck(e,t){for(let n of t)lk(e,n)}function lk(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&uk(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function uk(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 dk(e){let t=[...ek];for(let n=0;n<tk.length;n+=1){let r=tk[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(pk(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(pk(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 fk(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function pk(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var mk=`pi-webui.terminal.softKeys`,hk=`(pointer: coarse), (max-width: 760px)`;function gk(e,t){return e??t}function _k(e){if(e===`true`)return!0;if(e===`false`)return!1}function vk(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(hk):void 0}function yk(e){return e?.matches===!0}function bk(e=vk()){return gk(Sk(),yk(e))}function xk(){return Sk()!==void 0}function Sk(e=wk()){if(e!==void 0)try{return _k(e.getItem(mk))}catch{return}}function Ck(e,t=wk()){if(t!==void 0)try{t.setItem(mk,String(e))}catch{}}function wk(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var Tk=[{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`}],Ek=`\x1B`,Dk=``;function Ok(e,t){switch(e){case`escape`:return Ek;case`tab`:return` `;case`ctrl-c`:return kk(`c`);case`ctrl-d`:return kk(`d`);case`ctrl-z`:return kk(`z`);case`ctrl-l`:return kk(`l`);case`ctrl-r`:return kk(`r`);case`ctrl-u`:return kk(`u`);case`ctrl-w`:return kk(`w`);case`arrow-left`:return Ak(`D`,t);case`arrow-up`:return Ak(`A`,t);case`arrow-down`:return Ak(`B`,t);case`arrow-right`:return Ak(`C`,t);case`home`:return jk(`H`,t);case`end`:return jk(`F`,t);case`page-up`:return`${Ek}[5~`;case`page-down`:return`${Ek}[6~`;case`delete`:return`${Ek}[3~`;case`backspace`:return Dk;case`meta-backward-word`:return`${Ek}b`;case`meta-forward-word`:return`${Ek}f`}}function kk(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function Ak(e,t){return t?.applicationCursorKeysMode===!0?`${Ek}O${e}`:`${Ek}[${e}`}function jk(e,t){return t?.applicationCursorKeysMode===!0?`${Ek}O${e}`:`${Ek}[${e}`}var Mk=8,Nk=500,Pk=class extends y{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(Ok(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&&Fk(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||Fk(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<Nk){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return g`
5372
5372
  <div class="terminal-soft-keys" role="toolbar" aria-label="Terminal soft keys">
5373
- ${wk.map(e=>g`
5373
+ ${Tk.map(e=>g`
5374
5374
  <button
5375
5375
  type="button"
5376
5376
  class="soft-key"
@@ -5390,7 +5390,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5390
5390
  .terminal-soft-keys::-webkit-scrollbar { display: none; }
5391
5391
  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; }
5392
5392
  button:disabled { opacity: .5; cursor: not-allowed; }
5393
- `}};B([x({attribute:!1})],Nk.prototype,`modes`,void 0),B([x({type:Boolean})],Nk.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],Nk.prototype,`onInput`,void 0),Nk=B([b(`terminal-soft-keys`)],Nk);function Pk(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>jk}var Fk=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>qk,terminalBackgroundWithOpacity:()=>$k}),Ik={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},Lk={cols:100,rows:30},Rk=1e3,zk=`--pi-terminal-effective-bg`,Bk=`--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=yk(),this.suppressTerminalInput=!1,this.softKeysDefaultEnvironmentMedia=_k(),this.softKeysPreferenceStored=bk(),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=vk(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([Co.terminals(e.projectId,e.id,this.machineId),Co.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=Gf(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=Kf(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()??Lk,t=await Co.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 Co.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=Kf(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 Co.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&Wk(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()},Rk);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(Wk)}async cancelCommandRun(e){if(!(!Wk(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await Co.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 Co.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(Yk(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=jo(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=Kk(await Jk(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=eA(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(Yk(this)),r=new ie;n.loadAddon(r),n.open(t);let i=eA(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=Xk(this))}syncTerminalBackground(){let e=Qk(this.bgOpacity),t=$k(Zk(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(zk,t),this.style.setProperty(Bk,`${String(e)}%`)}sendTerminalInput(e){let t=qk(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(Wk(e)){let t=this.cancellingRunIds.includes(e.id);return g`
5393
+ `}};B([x({attribute:!1})],Pk.prototype,`modes`,void 0),B([x({type:Boolean})],Pk.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],Pk.prototype,`onInput`,void 0),Pk=B([b(`terminal-soft-keys`)],Pk);function Fk(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>Mk}var Ik=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>Jk,terminalBackgroundWithOpacity:()=>eA}),Lk={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},Rk={cols:100,rows:30},zk=1e3,Bk=`--pi-terminal-effective-bg`,Vk=`--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=bk(),this.suppressTerminalInput=!1,this.softKeysDefaultEnvironmentMedia=vk(),this.softKeysPreferenceStored=xk(),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=yk(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([Co.terminals(e.projectId,e.id,this.machineId),Co.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=Gf(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=Kf(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()??Rk,t=await Co.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 Co.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=Kf(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 Co.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&Gk(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()},zk);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(Gk)}async cancelCommandRun(e){if(!(!Gk(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await Co.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 Co.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(Xk(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=jo(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=qk(await Yk(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=tA(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(Xk(this)),r=new ie;n.loadAddon(r),n.open(t);let i=tA(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=Zk(this))}syncTerminalBackground(){let e=$k(this.bgOpacity),t=eA(Qk(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(Bk,t),this.style.setProperty(Vk,`${String(e)}%`)}sendTerminalInput(e){let t=Jk(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(Gk(e)){let t=this.cancellingRunIds.includes(e.id);return g`
5394
5394
  <section class="command-run-notice running">
5395
5395
  <div>
5396
5396
  <strong>${e.title}</strong>
@@ -5402,13 +5402,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5402
5402
  `}if(t?.exited===!0){let n=this.continuingTerminalIds.includes(t.id);return g`
5403
5403
  <section class=${`command-run-notice ${e.status}`}>
5404
5404
  <div>
5405
- <strong>${Gk(e)}</strong>
5405
+ <strong>${Kk(e)}</strong>
5406
5406
  <p>Output is preserved. Continue in a shell to inspect or run follow-up commands.</p>
5407
5407
  <code>${e.command}</code>
5408
5408
  </div>
5409
5409
  <button ?disabled=${n} @click=${()=>{this.continueTerminal(t.id)}}>${n?`Starting shell…`:`Continue in shell`}</button>
5410
5410
  </section>
5411
- `}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=nk(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=Vk(e.scrollTop,n,r),t.scrollLeft=Vk(e.scrollLeft,i,a)}async copyAllSnapshotText(){let e=this.copySnapshot?.text??``;if(e===``){this.copyStatus=`No terminal output to copy.`;return}this.copyStatus=await mb(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`
5411
+ `}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=rk(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=Hk(e.scrollTop,n,r),t.scrollLeft=Hk(e.scrollLeft,i,a)}async copyAllSnapshotText(){let e=this.copySnapshot?.text??``;if(e===``){this.copyStatus=`No terminal output to copy.`;return}this.copyStatus=await mb(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`
5412
5412
  <button
5413
5413
  type="button"
5414
5414
  class=${e?`copy-mode-toggle selected`:`copy-mode-toggle`}
@@ -5431,7 +5431,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5431
5431
  ${this.copyToolbarReplacesSoftKeys()?null:this.renderCopyModeToolbar()}
5432
5432
  <div class="terminal-copy-layers">
5433
5433
  <pre class="terminal-copy-content" aria-hidden="true">${e.lines.map((e,t)=>g`${t===0?null:`
5434
- `}${e.runs.map(e=>g`<span style=${XO(Uk(e.style))}>${e.text}</span>`)}`)}</pre>
5434
+ `}${e.runs.map(e=>g`<span style=${ZO(Wk(e.style))}>${e.text}</span>`)}`)}</pre>
5435
5435
  <textarea
5436
5436
  class="terminal-copy-selector"
5437
5437
  readonly
@@ -5446,7 +5446,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5446
5446
  ></textarea>
5447
5447
  </div>
5448
5448
  </section>
5449
- `}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,Sk(this.softKeysEnabled),this.scheduleFitAndNotify())}renderSoftKeysToggle(){return this.shouldShowSoftKeysToggle()?g`
5449
+ `}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,Ck(this.softKeysEnabled),this.scheduleFitAndNotify())}renderSoftKeysToggle(){return this.shouldShowSoftKeysToggle()?g`
5450
5450
  <button
5451
5451
  type="button"
5452
5452
  class=${this.softKeysEnabled?`soft-keys-toggle selected`:`soft-keys-toggle`}
@@ -5567,32 +5567,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5567
5567
  .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); }
5568
5568
  .muted { margin: 10px; color: var(--pi-muted); }
5569
5569
  .xterm { height: 100%; }
5570
- `}};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 Vk(e,t,n){return t<=0||n<=0?0:Math.min(1,Math.max(0,e/t))*n}function Hk(e){return/^#[\da-f]{6}$/i.test(e)?`${e}80`:`color-mix(in srgb, ${e} 50%, transparent)`}function Uk(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?Hk(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 Wk(e){return e.status===`queued`||e.status===`running`}function Gk(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 Kk(e){let t=JSON.parse(e);if(!nA(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 qk(e){return e.replaceAll(`\x1B[I`,``).replaceAll(`\x1B[O`,``)}async function Jk(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function Yk(e){let t=Ik;return e instanceof Z?{...t,fontSize:e.fontSize,theme:Xk(e)}:{...t,theme:Xk(e)}}function Xk(e){let t=$k(Zk(e,`--pi-terminal-bg`,`#05070a`),e instanceof Z?e.bgOpacity:100);return{...tk,background:t,foreground:Zk(e,`--pi-terminal-text`,`#e6edf3`),cursor:Zk(e,`--pi-accent`,`#58a6ff`),selectionBackground:Zk(e,`--pi-terminal-selection`,`#264f78`)}}function Zk(e,t,n){let r=getComputedStyle(e).getPropertyValue(t).trim();return r===``?n:r}function Qk(e){return Math.max(0,Math.min(100,e))}function $k(e,t){let n=Qk(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 eA(e){if(!(e===void 0||!tA(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function tA(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function nA(e){return typeof e==`object`&&!!e}var rA=class extends y{constructor(...e){super(...e),this.machines=[],this.activityRailOpen=!1,this.canScrollLeft=!1,this.canScrollRight=!1,this.handleToggleActivityRail=e=>{e.stopPropagation();let t=e.currentTarget;typeof HTMLElement>`u`||!(t instanceof HTMLElement)||this.onToggleActivityRail?.(t)},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=iA(this.machines),t=aA(this.machine),n=sA(this.project),r=lA(this.workspace),i=dA(this.session);return g`
5570
+ `}};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 Hk(e,t,n){return t<=0||n<=0?0:Math.min(1,Math.max(0,e/t))*n}function Uk(e){return/^#[\da-f]{6}$/i.test(e)?`${e}80`:`color-mix(in srgb, ${e} 50%, transparent)`}function Wk(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?Uk(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 Gk(e){return e.status===`queued`||e.status===`running`}function Kk(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 qk(e){let t=JSON.parse(e);if(!rA(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 Jk(e){return e.replaceAll(`\x1B[I`,``).replaceAll(`\x1B[O`,``)}async function Yk(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function Xk(e){let t=Lk;return e instanceof Z?{...t,fontSize:e.fontSize,theme:Zk(e)}:{...t,theme:Zk(e)}}function Zk(e){let t=eA(Qk(e,`--pi-terminal-bg`,`#05070a`),e instanceof Z?e.bgOpacity:100);return{...nk,background:t,foreground:Qk(e,`--pi-terminal-text`,`#e6edf3`),cursor:Qk(e,`--pi-accent`,`#58a6ff`),selectionBackground:Qk(e,`--pi-terminal-selection`,`#264f78`)}}function Qk(e,t,n){let r=getComputedStyle(e).getPropertyValue(t).trim();return r===``?n:r}function $k(e){return Math.max(0,Math.min(100,e))}function eA(e,t){let n=$k(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 tA(e){if(!(e===void 0||!nA(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function nA(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function rA(e){return typeof e==`object`&&!!e}var iA=class extends y{constructor(...e){super(...e),this.machines=[],this.activityRailOpen=!1,this.canScrollLeft=!1,this.canScrollRight=!1,this.handleToggleActivityRail=e=>{e.stopPropagation();let t=e.currentTarget;typeof HTMLElement>`u`||!(t instanceof HTMLElement)||this.onToggleActivityRail?.(t)},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=aA(this.machines),t=oA(this.machine),n=cA(this.project),r=uA(this.workspace),i=fA(this.session);return g`
5571
5571
  <nav class=${this.contextBarClass()} aria-label="Current location">
5572
5572
  <span class="context-bar-label">Location</span>
5573
5573
  <ol class="context-items" @scroll=${this.onContextScroll}>
5574
5574
  ${e?g`
5575
5575
  <li class="context-item">
5576
- <button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${oA(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
5576
+ <button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${sA(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
5577
5577
  <span class="context-kind">Machine</span>
5578
5578
  <span class="context-value">${t}</span>
5579
5579
  </button>
5580
5580
  </li>
5581
5581
  `:null}
5582
5582
  <li class="context-item">
5583
- <button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${cA(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
5583
+ <button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${lA(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
5584
5584
  <span class="context-kind">Project</span>
5585
5585
  <span class="context-value">${n}</span>
5586
5586
  </button>
5587
5587
  </li>
5588
5588
  <li class="context-item">
5589
- <button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${uA(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
5589
+ <button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${dA(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
5590
5590
  <span class="context-kind">Workspace</span>
5591
5591
  <span class="context-value">${r}</span>
5592
5592
  </button>
5593
5593
  </li>
5594
5594
  <li class="context-item">
5595
- <button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${fA(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
5595
+ <button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${pA(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
5596
5596
  <span class="context-kind">Session</span>
5597
5597
  <span class="context-value">${i}</span>
5598
5598
  </button>
@@ -5640,7 +5640,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5640
5640
  .context-kind { display: none; }
5641
5641
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
5642
5642
  button { cursor: pointer; }
5643
- `}};B([x({attribute:!1})],rA.prototype,`machines`,void 0),B([x({attribute:!1})],rA.prototype,`machine`,void 0),B([x({attribute:!1})],rA.prototype,`project`,void 0),B([x({attribute:!1})],rA.prototype,`workspace`,void 0),B([x({attribute:!1})],rA.prototype,`session`,void 0),B([x({attribute:!1})],rA.prototype,`refreshControl`,void 0),B([x({attribute:!1})],rA.prototype,`onOpenSection`,void 0),B([x({attribute:!1})],rA.prototype,`onShowActions`,void 0),B([x({type:Boolean})],rA.prototype,`activityRailOpen`,void 0),B([x({attribute:!1})],rA.prototype,`onToggleActivityRail`,void 0),B([C(`.context-items`)],rA.prototype,`contextItems`,void 0),B([S()],rA.prototype,`canScrollLeft`,void 0),B([S()],rA.prototype,`canScrollRight`,void 0),rA=B([b(`app-context-bar`)],rA);function iA(e){return e.length>1}function aA(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function oA(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function sA(e){return e?.name??`No project`}function cA(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function lA(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function uA(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function dA(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`:ty(e.id)}function fA(e){return e===void 0?`No session selected`:e.path}var pA=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`
5643
+ `}};B([x({attribute:!1})],iA.prototype,`machines`,void 0),B([x({attribute:!1})],iA.prototype,`machine`,void 0),B([x({attribute:!1})],iA.prototype,`project`,void 0),B([x({attribute:!1})],iA.prototype,`workspace`,void 0),B([x({attribute:!1})],iA.prototype,`session`,void 0),B([x({attribute:!1})],iA.prototype,`refreshControl`,void 0),B([x({attribute:!1})],iA.prototype,`onOpenSection`,void 0),B([x({attribute:!1})],iA.prototype,`onShowActions`,void 0),B([x({type:Boolean})],iA.prototype,`activityRailOpen`,void 0),B([x({attribute:!1})],iA.prototype,`onToggleActivityRail`,void 0),B([C(`.context-items`)],iA.prototype,`contextItems`,void 0),B([S()],iA.prototype,`canScrollLeft`,void 0),B([S()],iA.prototype,`canScrollRight`,void 0),iA=B([b(`app-context-bar`)],iA);function aA(e){return e.length>1}function oA(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function sA(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function cA(e){return e?.name??`No project`}function lA(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function uA(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function dA(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function fA(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`:ty(e.id)}function pA(e){return e===void 0?`No session selected`:e.path}var mA=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`
5644
5644
  <div class=${this.frameClass()}>
5645
5645
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
5646
5646
  ${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
@@ -5679,12 +5679,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5679
5679
  .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; }
5680
5680
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
5681
5681
  }
5682
- `}};B([x({attribute:!1})],pA.prototype,`tabs`,void 0),B([x({attribute:!1})],pA.prototype,`selectedView`,void 0),B([x({attribute:!1})],pA.prototype,`onSelect`,void 0),B([C(`.mobile-tabs`)],pA.prototype,`mobileTabs`,void 0),B([S()],pA.prototype,`canScrollLeft`,void 0),B([S()],pA.prototype,`canScrollRight`,void 0),pA=B([b(`app-mobile-main-tabs`)],pA);var mA=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=hA(e,this.statuses),n=e.name;return g`
5682
+ `}};B([x({attribute:!1})],mA.prototype,`tabs`,void 0),B([x({attribute:!1})],mA.prototype,`selectedView`,void 0),B([x({attribute:!1})],mA.prototype,`onSelect`,void 0),B([C(`.mobile-tabs`)],mA.prototype,`mobileTabs`,void 0),B([S()],mA.prototype,`canScrollLeft`,void 0),B([S()],mA.prototype,`canScrollRight`,void 0),mA=B([b(`app-mobile-main-tabs`)],mA);var hA=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=gA(e,this.statuses),n=e.name;return g`
5683
5683
  <div class="machine-switcher">
5684
5684
  <button
5685
5685
  type="button"
5686
5686
  class="machine-switcher-button"
5687
- title=${_A(e)}
5687
+ title=${vA(e)}
5688
5688
  aria-label=${this.machineSwitcherAriaLabel(e)}
5689
5689
  aria-expanded=${String(this.open)}
5690
5690
  @click=${e=>{this.toggleMenu(e.currentTarget)}}
@@ -5695,7 +5695,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5695
5695
  <span class="machine-switcher-kicker">Machine</span>
5696
5696
  <span class="machine-switcher-label">${n}</span>
5697
5697
  </span>
5698
- <span class=${`machine-status ${t}`}>${gA(t)}</span>
5698
+ <span class=${`machine-status ${t}`}>${_A(t)}</span>
5699
5699
  <span class="machine-chevron" aria-hidden="true">▾</span>
5700
5700
  </button>
5701
5701
  ${this.open?g`
@@ -5704,18 +5704,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5704
5704
  </div>
5705
5705
  `:null}
5706
5706
  </div>
5707
- `}renderMachineOption(e){let t=this.selected?.id===e.id,n=hA(e,this.statuses),r=Tv(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
5707
+ `}renderMachineOption(e){let t=this.selected?.id===e.id,n=gA(e,this.statuses),r=Tv(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
5708
5708
  <div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
5709
5709
  <button
5710
5710
  type="button"
5711
5711
  class="machine-option-main"
5712
- title=${_A(e)}
5712
+ title=${vA(e)}
5713
5713
  data-machine-id=${e.id}
5714
5714
  @click=${()=>{this.select(e)}}
5715
5715
  @keydown=${e=>{this.handleMachineOptionKeydown(e)}}
5716
5716
  >
5717
5717
  <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
5718
- <small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${gA(n)}</small>
5718
+ <small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${_A(n)}</small>
5719
5719
  </button>
5720
5720
  ${r?g`
5721
5721
  <div class="machine-option-actions">
@@ -5735,7 +5735,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5735
5735
  </div>
5736
5736
  `:null}
5737
5737
  </div>
5738
- `}renderActivity(e){let t=hA(e,this.statuses);if(t===`offline`||t===`error`)return;let n=oc(this.activities[e.id]);return cv(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=vA(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=vA(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=iv(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`
5738
+ `}renderActivity(e){let t=gA(e,this.statuses);if(t===`offline`||t===`error`)return;let n=oc(this.activities[e.id]);return cv(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=yA(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=yA(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=iv(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`
5739
5739
  :host { min-width: 0; display: block; }
5740
5740
  .machine-switcher { min-width: 0; }
5741
5741
  .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; }
@@ -5768,10 +5768,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5768
5768
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
5769
5769
  .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); }
5770
5770
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
5771
- `}};B([x({attribute:!1})],mA.prototype,`machines`,void 0),B([x({attribute:!1})],mA.prototype,`selected`,void 0),B([x({attribute:!1})],mA.prototype,`statuses`,void 0),B([x({attribute:!1})],mA.prototype,`activities`,void 0),B([x({attribute:!1})],mA.prototype,`onSelect`,void 0),B([x({attribute:!1})],mA.prototype,`onRemove`,void 0),B([x({attribute:!1})],mA.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],mA.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],mA.prototype,`open`,void 0),B([S()],mA.prototype,`menuStyle`,void 0),B([S()],mA.prototype,`openActionsMachineId`,void 0),B([S()],mA.prototype,`actionMenuStyle`,void 0),mA=B([b(`machine-switcher`)],mA);function hA(e,t){return t[e.id]?.status??e.status??`unknown`}function gA(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function _A(e){return e.baseUrl??e.name}function vA(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: ${yA(t.bottom)};`,`left: ${yA(r)};`,`width: ${yA(n)};`,`max-height: ${yA(i)};`].join(` `)}function yA(e){return`${String(Math.round(e))}px`}var bA=[{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`
5771
+ `}};B([x({attribute:!1})],hA.prototype,`machines`,void 0),B([x({attribute:!1})],hA.prototype,`selected`,void 0),B([x({attribute:!1})],hA.prototype,`statuses`,void 0),B([x({attribute:!1})],hA.prototype,`activities`,void 0),B([x({attribute:!1})],hA.prototype,`onSelect`,void 0),B([x({attribute:!1})],hA.prototype,`onRemove`,void 0),B([x({attribute:!1})],hA.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],hA.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],hA.prototype,`open`,void 0),B([S()],hA.prototype,`menuStyle`,void 0),B([S()],hA.prototype,`openActionsMachineId`,void 0),B([S()],hA.prototype,`actionMenuStyle`,void 0),hA=B([b(`machine-switcher`)],hA);function gA(e,t){return t[e.id]?.status??e.status??`unknown`}function _A(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function vA(e){return e.baseUrl??e.name}function yA(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: ${bA(t.bottom)};`,`left: ${bA(r)};`,`width: ${bA(n)};`,`max-height: ${bA(i)};`].join(` `)}function bA(e){return`${String(Math.round(e))}px`}var xA=[{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`
5772
5772
  <header>
5773
5773
  <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>
5774
- ${wA(this.machines)?g`
5774
+ ${TA(this.machines)?g`
5775
5775
  <machine-switcher
5776
5776
  .machines=${this.machines}
5777
5777
  .selected=${this.selectedMachine}
@@ -5788,7 +5788,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5788
5788
  <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
5789
5789
  </div>
5790
5790
  </header>
5791
- ${this.compact&&wA(this.machines)?g`
5791
+ ${this.compact&&TA(this.machines)?g`
5792
5792
  <machine-list
5793
5793
  .machines=${this.machines}
5794
5794
  .selected=${this.selectedMachine}
@@ -5878,9 +5878,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5878
5878
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
5879
5879
  ></session-list>
5880
5880
  <footer class="resource-underbar" aria-label="Resources">
5881
- ${bA.map(e=>xA(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
5881
+ ${xA.map(e=>SA(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
5882
5882
  </footer>
5883
- `}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=TA(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(EA(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
5883
+ `}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=EA(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(DA(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
5884
5884
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
5885
5885
  :host([compact]) { flex: 1 1 auto; }
5886
5886
  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); }
@@ -5912,12 +5912,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5912
5912
  :host([compact]) workspace-list[collapsed],
5913
5913
  :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
5914
5914
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
5915
- `}};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 xA(e,t,n,r){return g`
5916
- <button type="button" ?disabled=${!SA(e.id,n,r)} title=${e.label} aria-label=${e.label} @click=${t}>
5917
- ${CA(e.id)}
5915
+ `}};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 SA(e,t,n,r){return g`
5916
+ <button type="button" ?disabled=${!CA(e.id,n,r)} title=${e.label} aria-label=${e.label} @click=${t}>
5917
+ ${wA(e.id)}
5918
5918
  <span>${e.label}</span>
5919
5919
  </button>
5920
- `}function SA(e,t=!1,n=t){return e===`models`||e===`skills`&&t||e===`plugins`&&n}function CA(e){switch(e){case`models`:return _`
5920
+ `}function CA(e,t=!1,n=t){return e===`models`||e===`skills`&&t||e===`plugins`&&n}function wA(e){switch(e){case`models`:return _`
5921
5921
  <svg class="resource-underbar-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
5922
5922
  <rect x="4" y="4" width="16" height="16" rx="2"></rect>
5923
5923
  <rect x="9" y="9" width="6" height="6"></rect>
@@ -5935,7 +5935,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5935
5935
  <path d="M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0Z"></path>
5936
5936
  <path d="M12 19v3"></path>
5937
5937
  </svg>
5938
- `}}function wA(e){return e.length>1}function TA(e,t){let n=DA(t);return n[n.indexOf(e)-1]}function EA(e,t){let n=DA(t);return n[n.indexOf(e)+1]??`chat`}function DA(e){return Ng.filter(t=>t!==`machines`||wA(e))}var OA=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),kA=420,AA=4,jA=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`
5938
+ `}}function TA(e){return e.length>1}function EA(e,t){let n=OA(t);return n[n.indexOf(e)-1]}function DA(e,t){let n=OA(t);return n[n.indexOf(e)+1]??`chat`}function OA(e){return Ng.filter(t=>t!==`machines`||TA(e))}var kA=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),AA=420,jA=4,MA=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`
5939
5939
  ${this.renderResizeHandle()}
5940
5940
  <button
5941
5941
  type="button"
@@ -5965,7 +5965,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5965
5965
  @dblclick=${e=>{this.onResizeDoubleClick(e)}}
5966
5966
  @keydown=${e=>{this.onResizeKeyDown(e)}}
5967
5967
  ></div>
5968
- `}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)<=AA)&&(t.moved=!0,this.commitPanelWidth(Zg(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||!OA.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=Qg(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<=kA){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 $g(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.($g(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=Yg(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
5968
+ `}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)<=jA)&&(t.moved=!0,this.commitPanelWidth(Zg(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||!kA.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=Qg(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<=AA){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 $g(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.($g(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=Yg(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
5969
5969
  :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; }
5970
5970
  :host([side="navigation"]) { grid-column: 2; }
5971
5971
  :host([side="workspace"]) { grid-column: 4; }
@@ -5984,7 +5984,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5984
5984
  @media (max-width: 760px) {
5985
5985
  :host([side="navigation"]) { display: none; }
5986
5986
  }
5987
- `}};B([x({reflect:!0})],jA.prototype,`side`,void 0),B([x({type:Boolean,reflect:!0})],jA.prototype,`collapsed`,void 0),B([x({type:Boolean})],jA.prototype,`resizable`,void 0),B([x({type:Number})],jA.prototype,`panelWidth`,void 0),B([x({type:Number})],jA.prototype,`minWidth`,void 0),B([x({type:Number})],jA.prototype,`maxWidth`,void 0),B([x()],jA.prototype,`controls`,void 0),B([x()],jA.prototype,`resizeLabel`,void 0),B([x()],jA.prototype,`expandLabel`,void 0),B([x()],jA.prototype,`collapseLabel`,void 0),B([x({attribute:!1})],jA.prototype,`onToggle`,void 0),B([x({attribute:!1})],jA.prototype,`onResizeStart`,void 0),B([x({attribute:!1})],jA.prototype,`onResize`,void 0),B([x({attribute:!1})],jA.prototype,`onResizeEnd`,void 0),B([x({attribute:!1})],jA.prototype,`onReset`,void 0),jA=B([b(`app-panel-edge-control`)],jA);var MA=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
5987
+ `}};B([x({reflect:!0})],MA.prototype,`side`,void 0),B([x({type:Boolean,reflect:!0})],MA.prototype,`collapsed`,void 0),B([x({type:Boolean})],MA.prototype,`resizable`,void 0),B([x({type:Number})],MA.prototype,`panelWidth`,void 0),B([x({type:Number})],MA.prototype,`minWidth`,void 0),B([x({type:Number})],MA.prototype,`maxWidth`,void 0),B([x()],MA.prototype,`controls`,void 0),B([x()],MA.prototype,`resizeLabel`,void 0),B([x()],MA.prototype,`expandLabel`,void 0),B([x()],MA.prototype,`collapseLabel`,void 0),B([x({attribute:!1})],MA.prototype,`onToggle`,void 0),B([x({attribute:!1})],MA.prototype,`onResizeStart`,void 0),B([x({attribute:!1})],MA.prototype,`onResize`,void 0),B([x({attribute:!1})],MA.prototype,`onResizeEnd`,void 0),B([x({attribute:!1})],MA.prototype,`onReset`,void 0),MA=B([b(`app-panel-edge-control`)],MA);var NA=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
5988
5988
  <button
5989
5989
  class="app-refresh-button"
5990
5990
  title=${e}
@@ -6003,7 +6003,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6003
6003
  :host, :host * { -webkit-user-select: none; user-select: none; }
6004
6004
  .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; }
6005
6005
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
6006
- `}};B([x({attribute:!1})],MA.prototype,`onReload`,void 0),MA=B([b(`app-refresh-control`)],MA);var NA=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],PA=`file-manager`,FA=`browser`,IA=[...NA],LA=new Set(NA),RA=`pi-webui:activity-rail-order`;function zA(){return typeof localStorage>`u`?void 0:localStorage}function BA(e){return LA.has(e)}function VA(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===PA?`git-update-manager`:r;if(e!==FA){if(!BA(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===NA.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===NA.length?r:void 0}function HA(){try{let e=zA();if(e===void 0)return;let t=e.getItem(RA);return t===null?void 0:VA(JSON.parse(t))}catch{return}}function UA(e){try{let t=zA();if(t===void 0)return;t.setItem(RA,JSON.stringify(e))}catch{}}var WA=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function GA(e){return WA.includes(e)}function KA(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}var qA=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...IA],this.pluginItems=[],this.compactOpen=!1,this.onDesktopMediaChange=e=>{e.matches&&this.compactOpen&&this.onCloseCompact?.(),this.requestUpdate()},this.openTerminal=()=>{this.invokeCoreAction(this.onOpenTerminal)},this.openGitUpdateManager=()=>{this.invokeCoreAction(this.onOpenGitUpdateManager)},this.openTheme=()=>{this.invokeCoreAction(this.onOpenTheme)},this.openSystemPrompt=()=>{this.invokeCoreAction(this.onOpenSystemPrompt)},this.openHistory=()=>{this.invokeCoreAction(this.onOpenHistory)},this.openInfo=()=>{this.invokeCoreAction(this.onOpenInfo)},this.openSettings=()=>{this.invokeCoreAction(this.onOpenSettings)},this.openPluginActivity=(e,t)=>{this.closeCompactBeforeAction(),KA(t)&&this.onOpenPluginActivity?.(e,t)},this.closeCompact=()=>{this.onCloseCompact?.()},this.handleCompactBackdropMouseDown=e=>{e.target===e.currentTarget&&(e.preventDefault(),this.closeCompact())},this.handleCompactKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeCompact())},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||!GA(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(wg))}connectedCallback(){super.connectedCallback(),this.desktopMedia?.addEventListener(`change`,this.onDesktopMediaChange)}disconnectedCallback(){super.disconnectedCallback(),this.desktopMedia?.removeEventListener(`change`,this.onDesktopMediaChange)}updated(e){!e.has(`compactOpen`)||!this.compactOpen||this.isDesktopRailLayout()||this.renderRoot.querySelector(`.compact-rail-close`)?.focus()}isDesktopRailLayout(){return this.desktopMedia?.matches??!0}closeCompactBeforeAction(){this.isDesktopRailLayout()||this.onCloseCompact?.()}invokeCoreAction(e){this.closeCompactBeforeAction(),e?.()}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`
6006
+ `}};B([x({attribute:!1})],NA.prototype,`onReload`,void 0),NA=B([b(`app-refresh-control`)],NA);var PA=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],FA=`file-manager`,IA=`browser`,LA=[...PA],RA=new Set(PA),zA=`pi-webui:activity-rail-order`;function BA(){return typeof localStorage>`u`?void 0:localStorage}function VA(e){return RA.has(e)}function HA(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===FA?`git-update-manager`:r;if(e!==IA){if(!VA(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===PA.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===PA.length?r:void 0}function UA(){try{let e=BA();if(e===void 0)return;let t=e.getItem(zA);return t===null?void 0:HA(JSON.parse(t))}catch{return}}function WA(e){try{let t=BA();if(t===void 0)return;t.setItem(zA,JSON.stringify(e))}catch{}}var GA=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function KA(e){return GA.includes(e)}function qA(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}var JA=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...LA],this.pluginItems=[],this.compactOpen=!1,this.onDesktopMediaChange=e=>{e.matches&&this.compactOpen&&this.onCloseCompact?.(),this.requestUpdate()},this.openTerminal=()=>{this.invokeCoreAction(this.onOpenTerminal)},this.openGitUpdateManager=()=>{this.invokeCoreAction(this.onOpenGitUpdateManager)},this.openTheme=()=>{this.invokeCoreAction(this.onOpenTheme)},this.openSystemPrompt=()=>{this.invokeCoreAction(this.onOpenSystemPrompt)},this.openHistory=()=>{this.invokeCoreAction(this.onOpenHistory)},this.openInfo=()=>{this.invokeCoreAction(this.onOpenInfo)},this.openSettings=()=>{this.invokeCoreAction(this.onOpenSettings)},this.openPluginActivity=(e,t)=>{this.closeCompactBeforeAction(),qA(t)&&this.onOpenPluginActivity?.(e,t)},this.closeCompact=()=>{this.onCloseCompact?.()},this.handleCompactBackdropMouseDown=e=>{e.target===e.currentTarget&&(e.preventDefault(),this.closeCompact())},this.handleCompactKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeCompact())},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||!KA(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(wg))}connectedCallback(){super.connectedCallback(),this.desktopMedia?.addEventListener(`change`,this.onDesktopMediaChange)}disconnectedCallback(){super.disconnectedCallback(),this.desktopMedia?.removeEventListener(`change`,this.onDesktopMediaChange)}updated(e){!e.has(`compactOpen`)||!this.compactOpen||this.isDesktopRailLayout()||this.renderRoot.querySelector(`.compact-rail-close`)?.focus()}isDesktopRailLayout(){return this.desktopMedia?.matches??!0}closeCompactBeforeAction(){this.isDesktopRailLayout()||this.onCloseCompact?.()}invokeCoreAction(e){this.closeCompactBeforeAction(),e?.()}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`
6007
6007
  <button
6008
6008
  type="button"
6009
6009
  class="icon-button terminal-button"
@@ -6155,7 +6155,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6155
6155
  ${e.badge===void 0?v:g`<span class="rail-badge" aria-hidden="true">${e.badge}</span>`}
6156
6156
  </button>
6157
6157
  `}renderRailContents(){return g`
6158
- ${(this.railOrder.length===0?[...IA]:this.railOrder).map(e=>this.renderReorderableButton(e))}
6158
+ ${(this.railOrder.length===0?[...LA]:this.railOrder).map(e=>this.renderReorderableButton(e))}
6159
6159
  ${this.pluginItems.length===0?v:g`
6160
6160
  <div class="rail-plugin-separator" role="separator"></div>
6161
6161
  ${this.pluginItems.map(e=>this.renderPluginButton(e))}
@@ -6270,7 +6270,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6270
6270
  .compact-rail-dialog { height: 100%; }
6271
6271
  .compact-rail-dialog .rail { box-shadow: 8px 0 24px var(--pi-shadow); }
6272
6272
  .compact-rail-close { margin-bottom: 2px; }
6273
- `}};B([x({attribute:!1})],qA.prototype,`onOpenTerminal`,void 0),B([x({attribute:!1})],qA.prototype,`onOpenGitUpdateManager`,void 0),B([x({attribute:!1})],qA.prototype,`onOpenTheme`,void 0),B([x({attribute:!1})],qA.prototype,`onOpenSystemPrompt`,void 0),B([x({attribute:!1})],qA.prototype,`onOpenHistory`,void 0),B([x({attribute:!1})],qA.prototype,`onOpenInfo`,void 0),B([x({attribute:!1})],qA.prototype,`onOpenSettings`,void 0),B([x({type:Number})],qA.prototype,`terminalCount`,void 0),B([x({type:Number})],qA.prototype,`gitUpdateManagerCount`,void 0),B([x({type:Boolean})],qA.prototype,`systemPromptEnabled`,void 0),B([x({type:Boolean})],qA.prototype,`historyEnabled`,void 0),B([x({attribute:!1})],qA.prototype,`railOrder`,void 0),B([x({attribute:!1})],qA.prototype,`onRailOrderChange`,void 0),B([x({attribute:!1})],qA.prototype,`pluginItems`,void 0),B([x({attribute:!1})],qA.prototype,`onOpenPluginActivity`,void 0),B([x({type:Boolean})],qA.prototype,`compactOpen`,void 0),B([x({attribute:!1})],qA.prototype,`onCloseCompact`,void 0),qA=B([b(`activity-rail`)],qA);var JA=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},YA=class extends y{constructor(...e){super(...e),this.close=()=>{this.onClose?.()},this.handleCancel=e=>{e.preventDefault(),this.close()},this.handleBackdropClick=e=>{e.target===e.currentTarget&&this.close()}}firstUpdated(){let e=this.nativeDialog;e?.isConnected===!0&&(e.showModal(),this.closeButton?.focus())}disconnectedCallback(){let e=this.nativeDialog;e?.open===!0&&e.close(),super.disconnectedCallback()}render(){let e=$p(this.activity,this.context,this.onReportError??JA);return g`
6273
+ `}};B([x({attribute:!1})],JA.prototype,`onOpenTerminal`,void 0),B([x({attribute:!1})],JA.prototype,`onOpenGitUpdateManager`,void 0),B([x({attribute:!1})],JA.prototype,`onOpenTheme`,void 0),B([x({attribute:!1})],JA.prototype,`onOpenSystemPrompt`,void 0),B([x({attribute:!1})],JA.prototype,`onOpenHistory`,void 0),B([x({attribute:!1})],JA.prototype,`onOpenInfo`,void 0),B([x({attribute:!1})],JA.prototype,`onOpenSettings`,void 0),B([x({type:Number})],JA.prototype,`terminalCount`,void 0),B([x({type:Number})],JA.prototype,`gitUpdateManagerCount`,void 0),B([x({type:Boolean})],JA.prototype,`systemPromptEnabled`,void 0),B([x({type:Boolean})],JA.prototype,`historyEnabled`,void 0),B([x({attribute:!1})],JA.prototype,`railOrder`,void 0),B([x({attribute:!1})],JA.prototype,`onRailOrderChange`,void 0),B([x({attribute:!1})],JA.prototype,`pluginItems`,void 0),B([x({attribute:!1})],JA.prototype,`onOpenPluginActivity`,void 0),B([x({type:Boolean})],JA.prototype,`compactOpen`,void 0),B([x({attribute:!1})],JA.prototype,`onCloseCompact`,void 0),JA=B([b(`activity-rail`)],JA);var YA=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},XA=class extends y{constructor(...e){super(...e),this.close=()=>{this.onClose?.()},this.handleCancel=e=>{e.preventDefault(),this.close()},this.handleBackdropClick=e=>{e.target===e.currentTarget&&this.close()}}firstUpdated(){let e=this.nativeDialog;e?.isConnected===!0&&(e.showModal(),this.closeButton?.focus())}disconnectedCallback(){let e=this.nativeDialog;e?.open===!0&&e.close(),super.disconnectedCallback()}render(){let e=$p(this.activity,this.context,this.onReportError??YA);return g`
6274
6274
  <dialog
6275
6275
  class="plugin-activity-backdrop"
6276
6276
  role="dialog"
@@ -6332,7 +6332,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6332
6332
  header { padding-top: max(12px, env(safe-area-inset-top)); }
6333
6333
  .plugin-activity-body { padding-bottom: max(12px, env(safe-area-inset-bottom)); }
6334
6334
  }
6335
- `}};B([x({attribute:!1})],YA.prototype,`activity`,void 0),B([x({attribute:!1})],YA.prototype,`context`,void 0),B([x({attribute:!1})],YA.prototype,`onClose`,void 0),B([x({attribute:!1})],YA.prototype,`onReportError`,void 0),B([C(`dialog.plugin-activity-backdrop`)],YA.prototype,`nativeDialog`,void 0),B([C(`.plugin-activity-close`)],YA.prototype,`closeButton`,void 0),YA=B([b(`plugin-activity-dialog`)],YA);var XA=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.api=ko,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:QA(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=tj(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=M_(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`?A_(t.bounds,n,this.viewport()):j_(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`
6335
+ `}};B([x({attribute:!1})],XA.prototype,`activity`,void 0),B([x({attribute:!1})],XA.prototype,`context`,void 0),B([x({attribute:!1})],XA.prototype,`onClose`,void 0),B([x({attribute:!1})],XA.prototype,`onReportError`,void 0),B([C(`dialog.plugin-activity-backdrop`)],XA.prototype,`nativeDialog`,void 0),B([C(`.plugin-activity-close`)],XA.prototype,`closeButton`,void 0),XA=B([b(`plugin-activity-dialog`)],XA);var ZA=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.api=ko,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:$A(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=nj(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=M_(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`?A_(t.bounds,n,this.viewport()):j_(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`
6336
6336
  <div class="git-update-manager-backdrop" role="dialog" aria-modal="true" aria-label="Git Update Manager">
6337
6337
  <section class=${this.bounds===void 0?`git-update-manager-frame`:`git-update-manager-frame git-update-manager-frame-positioned`} style=${this.frameStyle()}>
6338
6338
  <header class="git-update-manager-header">
@@ -6366,15 +6366,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6366
6366
  ></div>
6367
6367
  </section>
6368
6368
  </div>
6369
- `}ensureWorkspaceScope(){let e=ej(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=zs(e.files);return t.staged.length===0&&t.unstaged.length===0?g`<p class="git-update-manager-empty">No Git changes.</p>`:g`
6369
+ `}ensureWorkspaceScope(){let e=tj(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=zs(e.files);return t.staged.length===0&&t.unstaged.length===0?g`<p class="git-update-manager-empty">No Git changes.</p>`:g`
6370
6370
  ${this.renderChangeGroup(`staged`,t.staged)}
6371
6371
  ${this.renderChangeGroup(`unstaged`,t.unstaged)}
6372
- `}renderChangeGroup(e,t){if(t.length===0)return null;let n=$A(e);return g`
6372
+ `}renderChangeGroup(e,t){if(t.length===0)return null;let n=ej(e);return g`
6373
6373
  <section class="git-update-manager-change-group" aria-label=${`${n} changes`}>
6374
6374
  <h2>${n} (${String(t.length)})</h2>
6375
6375
  ${t.map(e=>this.renderChange(e))}
6376
6376
  </section>
6377
- `}renderChange(e){let t=this.selectedChange?.id===e.id,n=Us(e),r=Hs(e.state),i=$A(e.scope);return g`
6377
+ `}renderChange(e){let t=this.selectedChange?.id===e.id,n=Us(e),r=Hs(e.state),i=ej(e.scope);return g`
6378
6378
  <button
6379
6379
  type="button"
6380
6380
  class=${`git-update-manager-entry ${t?`selected`:``}`}
@@ -6386,13 +6386,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6386
6386
  <span class="git-update-manager-path">${n}</span>
6387
6387
  <span class="git-update-manager-scope">${i}</span>
6388
6388
  </button>
6389
- `}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 ${Us(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${Us(e)}…</p>`;let t=this.selectedDiff;return ZA(),g`
6389
+ `}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 ${Us(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${Us(e)}…</p>`;let t=this.selectedDiff;return QA(),g`
6390
6390
  <header class="git-update-manager-diff-header">
6391
6391
  <strong>${Us(e)}</strong>
6392
- <small>${$A(e.scope)} · ${Hs(e.state)}${t.truncated?` · truncated`:``}</small>
6392
+ <small>${ej(e.scope)} · ${Hs(e.state)}${t.truncated?` · truncated`:``}</small>
6393
6393
  </header>
6394
6394
  <unified-diff-viewer .diff=${t.diff}></unified-diff-viewer>
6395
- `}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=tj(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=M_(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`
6395
+ `}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=nj(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=M_(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`
6396
6396
  :host { position: fixed; inset: 0; z-index: 80; color: var(--pi-text); font: 14px system-ui, sans-serif; }
6397
6397
  .git-update-manager-backdrop { width: 100%; height: 100dvh; display: grid; place-items: center; padding: 16px; background: rgba(0, 0, 0, .48); }
6398
6398
  .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); }
@@ -6431,7 +6431,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6431
6431
  .git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
6432
6432
  .git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
6433
6433
  }
6434
- `}};B([x({attribute:!1})],XA.prototype,`onClose`,void 0),B([x({attribute:!1})],XA.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],XA.prototype,`workspace`,void 0),B([x()],XA.prototype,`machineId`,void 0),B([x({attribute:!1})],XA.prototype,`api`,void 0),B([S()],XA.prototype,`status`,void 0),B([S()],XA.prototype,`selectedChange`,void 0),B([S()],XA.prototype,`selectedDiff`,void 0),B([S()],XA.prototype,`loadingStatus`,void 0),B([S()],XA.prototype,`loadingDiff`,void 0),B([S()],XA.prototype,`error`,void 0),B([S()],XA.prototype,`bounds`,void 0),XA=B([b(`git-update-manager-panel`)],XA);function ZA(){Xm(()=>import(`./UnifiedDiffViewer-DmskjbU5.js`),[],import.meta.url)}function QA(e,t){let n=zs(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function $A(e){return e===`staged`?`Staged`:`Unstaged`}function ej(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function tj(e){return e instanceof Error?e.message:String(e)}var nj=900*1e3,rj=750,ij=[1e3,3e3,8e3,15e3,3e4],aj={capture:!0},oj=`auto:on`,sj=`auto:off`,cj=`theme:`,lj=hs(`core:workspace.files`),uj=hs(`core:workspace.git`),dj=hs(`core:workspace.terminal`),fj=`workspace-memory`,pj=`workspace.memory`,mj=`workspace-memory:workspace.memory`,hj=320,gj=2,_j=`(min-width: 1181px)`,$=class extends y{constructor(...e){super(...e),this.state=rs(),this.sessionUnread=new Lp({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 df(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new vd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new cd,{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 yf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new _f,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new tc(()=>this.state,{workspaces:xo.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 lc(()=>this.state,e=>{this.setState(e)},{api:xo,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 ls(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new fs(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Zs(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new qs(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new dc(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new Os(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Ps(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new Ls(()=>this.state,e=>{this.setState(e)}),this.keyboard=new Yf,this.realtime=new Eu,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new jf,this.terminalSelection=new Wf,this.appShell=new Tg(this),this.browserResume=new Og({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Wg(this),this.panelResize=new Jg(this),this.navigationSections=new Vg(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=vj(),this.reportActivityRailError=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=am()??tm,this.activeThemeId=em,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=z_(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=q_(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=HA()??[...IA],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=h_(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=Lo(void 0),this.sessionWarningVisibility=Gp(),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=M_(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.closeCompactActivityRail=()=>{if(!this.compactRailOpen)return;this.compactRailOpen=!1;let e=this.compactActivityRailLauncher;this.updateComplete.then(()=>{!this.compactRailOpen&&this.activeActivityRailId===void 0&&(e===void 0?this.currentCompactActivityRailLauncher()?.focus():this.restoreActivityRailFocus(e))})},this.toggleCompactActivityRail=e=>{this.appShell.isDesktopActivityRailLayout||(!this.compactRailOpen&&e!==void 0&&(this.compactActivityRailLauncher=e),this.compactRailOpen=!this.compactRailOpen)},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.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.closeCompactActivityRail(),this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,UA(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`?A_(t.bounds,n,r):j_(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=L_(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=R_(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=Xp(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=xj(this.state),this.syncSelectedSessionReadState(),this.compactRailOpen&&this.appShell.isDesktopActivityRailLayout&&this.closeCompactActivityRail();let e=this.activeActivityRailId;e!==void 0&&this.activeActivityRailItem()===void 0&&this.closeActivityRailItem(e,this.activeActivityRailGeneration)}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=qp(this.sessionWarningVisibility,e===void 0?void 0:ss(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=bj(e,t);await this.updateComplete,!(!this.unreadConnected||xj(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);kj(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=$_(this.state.selectedProject?.name);this.windowTitleCleanup=ev(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=bj(e,t);return xj(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.compactRailOpen||this.activeActivityRailId!==void 0||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,aj),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},nj),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,aj),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(!Oj(this.state,e))return;let t=this.state;this.state={...this.state,...e},xj(t)!==xj(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),wj(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),Tj(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=u_();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=rj){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=>Dj(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 io.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=Lo(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(u_(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?Mj():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===``?Mj():{selectedFilePath:_s(lj,`file`),selectedDiffPath:_s(uj,`diff`),selectedTerminalId:_s(dj,`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){d_(e,{replace:!0}),vs(lj,`file`,void 0,{replace:!0}),vs(uj,`diff`,void 0,{replace:!0}),vs(dj,`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=Pj(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>=ij.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 Lj(),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(),d_({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(Nf(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Nf(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){d_(Pf(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){vs(lj,`file`,e.selectedFilePath,{replace:!0}),vs(uj,`diff`,e.selectedDiffPath,{replace:!0}),vs(dj,`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)??Mf(e.id);if(await this.restoreRouteFor(Pf(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=Nj(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=S_(e,{api:{runTerminalCommand:(e,n)=>Co.runTerminalCommand(e,n,t),listCommandRuns:e=>Co.listCommandRuns(e,t),getCommandRun:e=>Co.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){vs(dj,`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,g_(e)}closeSettings(){this.settingsSection=void 0,g_(void 0)}navigateSettings(e){this.settingsSection=e,g_(e)}restoreSettingsRoute(){this.settingsSection=h_()}handleWorkspaceChange(e,t){let n=Cj(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 So.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`:Kt(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 Eu;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=>Ej(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):jj(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 Co.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=Aj(e),r=Aj(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`
6434
+ `}};B([x({attribute:!1})],ZA.prototype,`onClose`,void 0),B([x({attribute:!1})],ZA.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],ZA.prototype,`workspace`,void 0),B([x()],ZA.prototype,`machineId`,void 0),B([x({attribute:!1})],ZA.prototype,`api`,void 0),B([S()],ZA.prototype,`status`,void 0),B([S()],ZA.prototype,`selectedChange`,void 0),B([S()],ZA.prototype,`selectedDiff`,void 0),B([S()],ZA.prototype,`loadingStatus`,void 0),B([S()],ZA.prototype,`loadingDiff`,void 0),B([S()],ZA.prototype,`error`,void 0),B([S()],ZA.prototype,`bounds`,void 0),ZA=B([b(`git-update-manager-panel`)],ZA);function QA(){Xm(()=>import(`./UnifiedDiffViewer-DVWEwLh_.js`),[],import.meta.url)}function $A(e,t){let n=zs(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function ej(e){return e===`staged`?`Staged`:`Unstaged`}function tj(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function nj(e){return e instanceof Error?e.message:String(e)}var rj=900*1e3,ij=750,aj=[1e3,3e3,8e3,15e3,3e4],oj={capture:!0},sj=`auto:on`,cj=`auto:off`,lj=`theme:`,uj=hs(`core:workspace.files`),dj=hs(`core:workspace.git`),fj=hs(`core:workspace.terminal`),pj=`workspace-memory`,mj=`workspace.memory`,hj=`workspace-memory:workspace.memory`,gj=320,_j=2,vj=`(min-width: 1181px)`,$=class extends y{constructor(...e){super(...e),this.state=rs(),this.sessionUnread=new Lp({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 df(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new vd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new cd,{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 yf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new _f,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new tc(()=>this.state,{workspaces:xo.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 lc(()=>this.state,e=>{this.setState(e)},{api:xo,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 ls(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new fs(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Zs(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new qs(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new dc(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new Os(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Ps(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new Ls(()=>this.state,e=>{this.setState(e)}),this.keyboard=new Yf,this.realtime=new Eu,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new jf,this.terminalSelection=new Wf,this.appShell=new Tg(this),this.browserResume=new Og({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Wg(this),this.panelResize=new Jg(this),this.navigationSections=new Vg(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=yj(),this.reportActivityRailError=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=am()??tm,this.activeThemeId=em,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=z_(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=q_(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=UA()??[...LA],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=h_(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=Lo(void 0),this.sessionWarningVisibility=Gp(),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=M_(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.closeCompactActivityRail=()=>{if(!this.compactRailOpen)return;this.compactRailOpen=!1;let e=this.compactActivityRailLauncher;this.updateComplete.then(()=>{!this.compactRailOpen&&this.activeActivityRailId===void 0&&(e===void 0?this.currentCompactActivityRailLauncher()?.focus():this.restoreActivityRailFocus(e))})},this.toggleCompactActivityRail=e=>{this.appShell.isDesktopActivityRailLayout||(!this.compactRailOpen&&e!==void 0&&(this.compactActivityRailLauncher=e),this.compactRailOpen=!this.compactRailOpen)},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.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.closeCompactActivityRail(),this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,WA(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`?A_(t.bounds,n,r):j_(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=L_(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=R_(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=Xp(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=Sj(this.state),this.syncSelectedSessionReadState(),this.compactRailOpen&&this.appShell.isDesktopActivityRailLayout&&this.closeCompactActivityRail();let e=this.activeActivityRailId;e!==void 0&&this.activeActivityRailItem()===void 0&&this.closeActivityRailItem(e,this.activeActivityRailGeneration)}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=qp(this.sessionWarningVisibility,e===void 0?void 0:ss(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=xj(e,t);await this.updateComplete,!(!this.unreadConnected||Sj(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);Aj(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=$_(this.state.selectedProject?.name);this.windowTitleCleanup=ev(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=xj(e,t);return Sj(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.compactRailOpen||this.activeActivityRailId!==void 0||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,oj),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},rj),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,oj),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(!kj(this.state,e))return;let t=this.state;this.state={...this.state,...e},Sj(t)!==Sj(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),Tj(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),Ej(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=u_();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=ij){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=>Oj(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 io.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=Lo(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(u_(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?Nj():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===``?Nj():{selectedFilePath:_s(uj,`file`),selectedDiffPath:_s(dj,`diff`),selectedTerminalId:_s(fj,`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){d_(e,{replace:!0}),vs(uj,`file`,void 0,{replace:!0}),vs(dj,`diff`,void 0,{replace:!0}),vs(fj,`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=Fj(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>=aj.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 Rj(),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(),d_({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(Nf(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Nf(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){d_(Pf(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){vs(uj,`file`,e.selectedFilePath,{replace:!0}),vs(dj,`diff`,e.selectedDiffPath,{replace:!0}),vs(fj,`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)??Mf(e.id);if(await this.restoreRouteFor(Pf(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=Pj(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=S_(e,{api:{runTerminalCommand:(e,n)=>Co.runTerminalCommand(e,n,t),listCommandRuns:e=>Co.listCommandRuns(e,t),getCommandRun:e=>Co.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){vs(fj,`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,g_(e)}closeSettings(){this.settingsSection=void 0,g_(void 0)}navigateSettings(e){this.settingsSection=e,g_(e)}restoreSettingsRoute(){this.settingsSection=h_()}handleWorkspaceChange(e,t){let n=wj(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 So.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`:Kt(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 Eu;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=>Dj(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):Mj(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 Co.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=jj(e),r=jj(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`
6435
6435
  <workspace-panel
6436
6436
  id="workspace-panel"
6437
6437
  .workspace=${e}
@@ -6478,7 +6478,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6478
6478
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
6479
6479
  .onReset=${()=>{this.resetResizablePanel(`workspace`)}}
6480
6480
  ></app-panel-edge-control>
6481
- `}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-gj-hj);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(_j).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||Kt(e,T.sessionsDeleteArchived)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Kt(e,T.sessionsReload)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Kt(e,T.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Kt(e,T.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Kt(e,T.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Kt(e,T.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return Yu(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&Kt(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 So.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: ${Fj(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Cp(t.previewRequest)!==Cp(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 So.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: ${Fj(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 So.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: ${Fj(e)}`})}}renderNavigationPanel(){return g`
6481
+ `}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-_j-gj);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(vj).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||Kt(e,T.sessionsDeleteArchived)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Kt(e,T.sessionsReload)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Kt(e,T.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Kt(e,T.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Kt(e,T.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Kt(e,T.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return Yu(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&Kt(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 So.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: ${Ij(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Cp(t.previewRequest)!==Cp(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 So.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: ${Ij(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 So.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: ${Ij(e)}`})}}renderNavigationPanel(){return g`
6482
6482
  <app-navigation-panel
6483
6483
  .machines=${this.state.machines}
6484
6484
  .selectedMachine=${this.state.selectedMachine}
@@ -6554,14 +6554,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6554
6554
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
6555
6555
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
6556
6556
  ></app-navigation-panel>
6557
- `}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`&&!wA(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 Lj(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await Lj(),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`
6557
+ `}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`&&!TA(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 Rj(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await Rj(),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`
6558
6558
  <session-tree-navigator
6559
6559
  .tree=${e.treeDialog}
6560
6560
  .onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
6561
6561
  .onAbort=${()=>this.sessions.abortTreeNavigation()}
6562
6562
  .onCancel=${()=>{this.closeSessionTreeNavigator()}}
6563
6563
  ></session-tree-navigator>
6564
- `}workspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}synchronizeMemoryPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.memory.updatePolling(!1);return}this.synchronizeMemoryPolling(e)}synchronizeMemoryPolling(e){let t=e.some(e=>Sj(e)&&Zp(e,this.createActivityRailContext(e.id),this.reportActivityRailError));this.memory.updatePolling(t)}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`
6564
+ `}workspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}synchronizeMemoryPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.memory.updatePolling(!1);return}this.synchronizeMemoryPolling(e)}synchronizeMemoryPolling(e){let t=e.some(e=>Cj(e)&&Zp(e,this.createActivityRailContext(e.id),this.reportActivityRailError));this.memory.updatePolling(t)}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`
6565
6565
  <section class="session-start-screen" aria-labelledby="session-start-heading">
6566
6566
  <div class="session-start-content">
6567
6567
  <p class="session-start-eyebrow">PI WEBUI · ${t.label}</p>
@@ -6573,7 +6573,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6573
6573
  <p class="session-start-hint">Describe a goal, paste a task, or attach a file to begin.</p>
6574
6574
  </div>
6575
6575
  </section>
6576
- `}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=yj(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=>xo.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await xo.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await xo.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await xo.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelTerminal(e,t,n){let r=this.terminalCommandRunsForOrigin(n,t);return{open:n=>{this.openRuntimeTerminal(t,e,n)},runCommand:t=>r.runCommand({...t,workspace:e})}}createWorkspacePanelContext(e){let t=yj(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return dg({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:this.createWorkspacePanelTerminal(e,n,i),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:Ro(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 y_(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`,()=>Kh())}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}`,()=>Kh(`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.synchronizeMemoryPollingForSelectedWorkspace(),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(){return this.createPluginRuntimeContextForOrigin(`core`,R(this.state))}createPluginRuntimeContextForOrigin(e,t){let n=e=>ug({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(e,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()},n);return n(e)}createActivityRailContext(e){let t=yj(this.state),n=this.state.selectedWorkspace,r=this.activeActivityRailId===e?this.activeActivityRailGeneration:void 0,i=a=>fg({...this.createPluginRuntimeContextForOrigin(a,t.id),machine:t,...n===void 0?{}:{workspaceScope:{workspace:n,files:this.createWorkspaceFiles(n,t.id),terminal:this.createWorkspacePanelTerminal(n,t.id,a)}},host:{requestRender:()=>{this.requestUpdate()},close:()=>{r!==void 0&&this.closeActivityRailItem(e,r)}},onRefreshMemory:()=>{this.memory.refresh()}},i);return i(`core`)}activityRailItems(){let e=this.plugins.getActivityRailItems();return this.synchronizeMemoryPollingForSelectedWorkspace(e),e.flatMap(e=>this.projectActivityRailItems([e],this.createActivityRailContext(e.id)))}projectActivityRailItems(e,t){return Qp(e,t,this.reportActivityRailError)}activeActivityRailItem(){let e=this.activeActivityRailId;if(e===void 0)return;let t=this.resolveActivityRailItem(e);return t===void 0?void 0:{...t,generation:this.activeActivityRailGeneration}}openActivityRailItem(e,t){this.resolveActivityRailItem(e)!==void 0&&(this.closeCompactActivityRail(),this.activityRailRestoreFocus=t,this.activeActivityRailGeneration+=1,this.activeActivityRailId=e)}resolveActivityRailItem(e){let t=this.plugins.getActivityRailItems().find(t=>t.id===e);if(t===void 0)return;let n=this.createActivityRailContext(e);if(this.projectActivityRailItems([t],n).some(t=>t.id===e))return{activity:t,context:n}}closeActivityRailItem(e,t){if(this.activeActivityRailId!==e||this.activeActivityRailGeneration!==t)return;let n=this.activityRailRestoreFocus;this.activityRailRestoreFocus=void 0,this.activeActivityRailId=void 0,n!==void 0&&this.updateComplete.then(()=>{this.activeActivityRailId===void 0&&n()})}restoreActivityRailFocus(e){if(e.isConnected){e.focus();return}let t=this.compactActivityRailLauncher;if(t?.isConnected===!0){t.focus();return}this.currentCompactActivityRailLauncher()?.focus()}currentCompactActivityRailLauncher(){let e=this.renderRoot.querySelector(`app-context-bar`)?.shadowRoot?.querySelector(`.activity-rail-action-button`);return e?.isConnected===!0?e:void 0}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!bf(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(xm(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 xo.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: ${Fj(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=Sm(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(vm(t.id));if(R(this.state)!==e)return;let r=ym(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Cm(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(Cm);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=Nj(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Sm(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:Ij(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?sj:oj;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${cj}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${cj}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===oj||e===sj){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===oj},this.applyPreferredTheme(!0);return}if(!e.startsWith(cj))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,sm(t),e&&om(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return cm({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return um(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=Rj(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=Rj(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 So.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=M_(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(){B_({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,this.persistWorkspaceTabVisibility()}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,this.persistWorkspaceTabVisibility()}persistWorkspaceTabVisibility(){J_({terminalHidden:this.terminalTabHidden,infoHidden:this.infoTabHidden})}renderChatView(e,t){return g`
6576
+ `}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=bj(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=>xo.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await xo.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await xo.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await xo.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelTerminal(e,t,n){let r=this.terminalCommandRunsForOrigin(n,t);return{open:n=>{this.openRuntimeTerminal(t,e,n)},runCommand:t=>r.runCommand({...t,workspace:e})}}createWorkspacePanelContext(e){let t=bj(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return dg({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:this.createWorkspacePanelTerminal(e,n,i),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:Ro(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 y_(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`,()=>Kh())}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}`,()=>Kh(`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.synchronizeMemoryPollingForSelectedWorkspace(),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(){return this.createPluginRuntimeContextForOrigin(`core`,R(this.state))}createPluginRuntimeContextForOrigin(e,t){let n=e=>ug({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(e,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()},n);return n(e)}createActivityRailContext(e){let t=bj(this.state),n=this.state.selectedWorkspace,r=this.activeActivityRailId===e?this.activeActivityRailGeneration:void 0,i=a=>fg({...this.createPluginRuntimeContextForOrigin(a,t.id),machine:t,...n===void 0?{}:{workspaceScope:{workspace:n,files:this.createWorkspaceFiles(n,t.id),terminal:this.createWorkspacePanelTerminal(n,t.id,a)}},host:{requestRender:()=>{this.requestUpdate()},close:()=>{r!==void 0&&this.closeActivityRailItem(e,r)}},onRefreshMemory:()=>{this.memory.refresh()}},i);return i(`core`)}activityRailItems(){let e=this.plugins.getActivityRailItems();return this.synchronizeMemoryPollingForSelectedWorkspace(e),e.flatMap(e=>this.projectActivityRailItems([e],this.createActivityRailContext(e.id)))}projectActivityRailItems(e,t){return Qp(e,t,this.reportActivityRailError)}activeActivityRailItem(){let e=this.activeActivityRailId;if(e===void 0)return;let t=this.resolveActivityRailItem(e);return t===void 0?void 0:{...t,generation:this.activeActivityRailGeneration}}openActivityRailItem(e,t){this.resolveActivityRailItem(e)!==void 0&&(this.closeCompactActivityRail(),this.activityRailRestoreFocus=t,this.activeActivityRailGeneration+=1,this.activeActivityRailId=e)}resolveActivityRailItem(e){let t=this.plugins.getActivityRailItems().find(t=>t.id===e);if(t===void 0)return;let n=this.createActivityRailContext(e);if(this.projectActivityRailItems([t],n).some(t=>t.id===e))return{activity:t,context:n}}closeActivityRailItem(e,t){if(this.activeActivityRailId!==e||this.activeActivityRailGeneration!==t)return;let n=this.activityRailRestoreFocus;this.activityRailRestoreFocus=void 0,this.activeActivityRailId=void 0,n!==void 0&&this.updateComplete.then(()=>{this.activeActivityRailId===void 0&&n()})}restoreActivityRailFocus(e){if(e.isConnected){e.focus();return}let t=this.compactActivityRailLauncher;if(t?.isConnected===!0){t.focus();return}this.currentCompactActivityRailLauncher()?.focus()}currentCompactActivityRailLauncher(){let e=this.renderRoot.querySelector(`app-context-bar`)?.shadowRoot?.querySelector(`.activity-rail-action-button`);return e?.isConnected===!0?e:void 0}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!bf(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(xm(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 xo.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: ${Ij(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=Sm(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(vm(t.id));if(R(this.state)!==e)return;let r=ym(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Cm(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(Cm);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=Pj(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Sm(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:Lj(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?cj:sj;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${lj}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${lj}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===sj||e===cj){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===sj},this.applyPreferredTheme(!0);return}if(!e.startsWith(lj))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,sm(t),e&&om(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return cm({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return um(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=zj(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=zj(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 So.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=M_(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(){B_({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,this.persistWorkspaceTabVisibility()}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,this.persistWorkspaceTabVisibility()}persistWorkspaceTabVisibility(){J_({terminalHidden:this.terminalTabHidden,infoHidden:this.infoTabHidden})}renderChatView(e,t){return g`
6577
6577
  <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=${Gd(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>
6578
6578
  `}renderContextBar(){return this.appShell.isDesktopActivityRailLayout?null:g`
6579
6579
  <app-context-bar
@@ -6748,4 +6748,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6748
6748
  ${this.terminalModalOpen?this.renderTerminalModal():null}
6749
6749
  ${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>`}
6750
6750
  </div>
6751
- `}static{this.styles=Rm}};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,`compactRailOpen`,void 0),B([S()],$.prototype,`activeActivityRailId`,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 vj(){let e=new og;return e.register({id:`core`,plugin:Ih}),e.register({id:`themes`,plugin:Bh}),e}function yj(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 bj(e,t){return JSON.stringify([e,t.id,t.cwd])}function xj(e){let t=e.selectedSession;return t===void 0?void 0:bj(R(e),t)}function Sj(e){return e.id===mj||e.sourcePluginId===fj&&e.localId===pj}function Cj(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 wj(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function Tj(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function Ej(e,t){return Dj(e,t)}function Dj(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function Oj(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function kj(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function Aj(e){return is(e.status,e.activity)}function jj(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function Mj(){return{}}function Nj(e,t){return JSON.stringify([e,t])}function Pj(e){return ij[Math.min(e,ij.length-1)]??3e4}function Fj(e){return e instanceof Error?e.message:String(e)}function Ij(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Lj(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function Rj(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};
6751
+ `}static{this.styles=Rm}};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,`compactRailOpen`,void 0),B([S()],$.prototype,`activeActivityRailId`,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 yj(){let e=new og;return e.register({id:`core`,plugin:Ih}),e.register({id:`themes`,plugin:Bh}),e}function bj(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 xj(e,t){return JSON.stringify([e,t.id,t.cwd])}function Sj(e){let t=e.selectedSession;return t===void 0?void 0:xj(R(e),t)}function Cj(e){return e.id===hj||e.sourcePluginId===pj&&e.localId===mj}function wj(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 Tj(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function Ej(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function Dj(e,t){return Oj(e,t)}function Oj(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function kj(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function Aj(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function jj(e){return is(e.status,e.activity)}function Mj(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function Nj(){return{}}function Pj(e,t){return JSON.stringify([e,t])}function Fj(e){return aj[Math.min(e,aj.length-1)]??3e4}function Ij(e){return e instanceof Error?e.message:String(e)}function Lj(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Rj(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function zj(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};