@vincenthanxiaodu/pi-web 1.202608.39 → 1.202608.41

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-DWMYXHbj.js","./vendor-editor-core-CXO8gGab.js","./vendor-editor-languages-CpW4sJsX.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-FojQLt0o.js","./vendor-terminal-D8k4UKM2.js","./vendor-terminal-BrP-ENHg.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-935R1s95.js","./vendor-editor-core-CXO8gGab.js","./vendor-editor-languages-CpW4sJsX.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-BY9VIA1-.js","./vendor-terminal-D8k4UKM2.js","./vendor-terminal-BrP-ENHg.css"])))=>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,Y as o,Z as s,d as c,et as l,f as u,j as d,l as f,p,q as m,u as ee}from"./vendor-editor-core-CXO8gGab.js";import{a as te,o as ne,s as re}from"./vendor-editor-languages-CpW4sJsX.js";(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 ie=globalThis,ae=ie.ShadowRoot&&(ie.ShadyCSS===void 0||ie.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,oe=Symbol(),se=new WeakMap,ce=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==oe)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(ae&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=se.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&se.set(t,e))}return e}toString(){return this.cssText}},le=e=>new ce(typeof e==`string`?e:e+``,void 0,oe),h=(e,...t)=>new ce(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,oe),ue=(e,t)=>{if(ae)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=ie.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},de=ae?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return le(t)})(e):e,{is:fe,defineProperty:pe,getOwnPropertyDescriptor:me,getOwnPropertyNames:he,getOwnPropertySymbols:ge,getPrototypeOf:_e}=Object,ve=globalThis,ye=ve.trustedTypes,be=ye?ye.emptyScript:``,xe=ve.reactiveElementPolyfillSupport,Se=(e,t)=>e,Ce={toAttribute(e,t){switch(t){case Boolean:e=e?be: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}},we=(e,t)=>!fe(e,t),Te={attribute:!0,type:String,converter:Ce,reflect:!1,useDefault:!1,hasChanged:we};Symbol.metadata??=Symbol(`metadata`),ve.litPropertyMetadata??=new WeakMap;var Ee=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=Te){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&&pe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=me(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)??Te}static _$Ei(){if(this.hasOwnProperty(Se(`elementProperties`)))return;let e=_e(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Se(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Se(`properties`))){let e=this.properties,t=[...he(e),...ge(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(de(e))}else e!==void 0&&t.push(de(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 ue(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?Ce: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?Ce: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??we)(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){}};Ee.elementStyles=[],Ee.shadowRootOptions={mode:`open`},Ee[Se(`elementProperties`)]=new Map,Ee[Se(`finalized`)]=new Map,xe?.({ReactiveElement:Ee}),(ve.reactiveElementVersions??=[]).push(`2.1.2`);var De=globalThis,Oe=e=>e,ke=De.trustedTypes,Ae=ke?ke.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,je=`$lit$`,Me=`lit$${Math.random().toFixed(9).slice(2)}$`,Ne=`?`+Me,Pe=`<${Ne}>`,Fe=document,Ie=()=>Fe.createComment(``),Le=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Re=Array.isArray,ze=e=>Re(e)||typeof e?.[Symbol.iterator]==`function`,Be=`[
3
3
  \f\r]`,Ve=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,He=/-->/g,Ue=/>/g,We=RegExp(`>|${Be}(?:([^\\s"'>=/]+)(${Be}*=${Be}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Ge=/'/g,Ke=/"/g,qe=/^(?:script|style|textarea|title)$/i,Je=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=Je(1),Ye=Je(2),Xe=Symbol.for(`lit-noChange`),_=Symbol.for(`lit-nothing`),Ze=new WeakMap,Qe=Fe.createTreeWalker(Fe,129);function $e(e,t){if(!Re(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ae===void 0?t:Ae.createHTML(t)}var et=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Ve;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===Ve?c[1]===`!--`?o=He:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=We):(qe.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=We):o=Ue:o===We?c[0]===`>`?(o=i??Ve,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?We:c[3]===`"`?Ke:Ge):o===Ke||o===Ge?o=We:o===He||o===Ue?o=Ve:(o=We,i=void 0);let d=o===We&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Ve?n+Pe:l>=0?(r.push(s),n.slice(0,l)+je+n.slice(l)+Me+d):n+Me+(l===-2?t:d)}return[$e(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},tt=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]=et(t,n);if(this.el=e.createElement(l,r),Qe.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=Qe.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(je)){let t=u[o++],n=i.getAttribute(e).split(Me),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ot:r[1]===`?`?st:r[1]===`@`?ct:at}),i.removeAttribute(e)}else e.startsWith(Me)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(qe.test(i.tagName)){let e=i.textContent.split(Me),t=e.length-1;if(t>0){i.textContent=ke?ke.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Ie()),Qe.nextNode(),c.push({type:2,index:++a});i.append(e[t],Ie())}}}else if(i.nodeType===8)if(i.data===Ne)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Me,e+1))!==-1;)c.push({type:7,index:a}),e+=Me.length-1}a++}}static createElement(e,t){let n=Fe.createElement(`template`);return n.innerHTML=e,n}};function nt(e,t,n=e,r){if(t===Xe)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Le(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=nt(e,i._$AS(e,t.values),i,r)),t}var rt=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??Fe).importNode(t,!0);Qe.currentNode=r;let i=Qe.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new it(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new lt(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=Qe.nextNode(),a++)}return Qe.currentNode=Fe,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++}},it=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=_,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=nt(this,e,t),Le(e)?e===_||e==null||e===``?(this._$AH!==_&&this._$AR(),this._$AH=_):e!==this._$AH&&e!==Xe&&this._(e):e._$litType$===void 0?e.nodeType===void 0?ze(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!==_&&Le(this._$AH)?this._$AA.nextSibling.data=e:this.T(Fe.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=tt.createElement($e(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new rt(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=Ze.get(e.strings);return t===void 0&&Ze.set(e.strings,t=new tt(e)),t}k(t){Re(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(Ie()),this.O(Ie()),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=Oe(e).nextSibling;Oe(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},at=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=_,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=_}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=nt(this,e,t,0),a=!Le(e)||e!==this._$AH&&e!==Xe,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=nt(this,r[n+o],t,o),s===Xe&&(s=this._$AH[o]),a||=!Le(s)||s!==this._$AH[o],s===_?e=_:e!==_&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===_?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},ot=class extends at{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===_?void 0:e}},st=class extends at{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==_)}},ct=class extends at{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=nt(this,e,t,0)??_)===Xe)return;let n=this._$AH,r=e===_&&n!==_||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==_&&(n===_||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)}},lt=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){nt(this,e)}},ut={M:je,P:Me,A:Ne,C:1,L:et,R:rt,D:ze,V:nt,I:it,H:at,N:st,U:ct,B:ot,F:lt},dt=De.litHtmlPolyfillSupport;dt?.(tt,it),(De.litHtmlVersions??=[]).push(`3.3.3`);var ft=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new it(t.insertBefore(Ie(),e),e,void 0,n??{})}return i._$AI(e),i},pt=globalThis,v=class extends Ee{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=ft(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Xe}};v._$litElement$=!0,v.finalized=!0,pt.litElementHydrateSupport?.({LitElement:v});var mt=pt.litElementPolyfillSupport;mt?.({LitElement:v}),(pt.litElementVersions??=[]).push(`4.2.2`);var y=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},ht={attribute:!0,type:String,converter:Ce,reflect:!1,hasChanged:we},gt=(e=ht,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 b(e){return(t,n)=>typeof n==`object`?gt(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 x(e){return b({...e,state:!0,attribute:!1})}var _t=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function S(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 _t(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 _t(n,r,{get(){return a(this)}})}}function vt(e,t=bt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(xt(e),n).toString()}function yt(e,t=bt()){let n=new URL(vt(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 bt(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function xt(e){return e.startsWith(`/`)?`.${e}`:e}var St;function Ct(e){St=e}function wt(){let e=St;if(e!==void 0)try{e()}catch{}}var Tt=class extends Error{constructor(e,t){super(e),this.status=t,this.name=`HttpError`}};function Et(e){return e instanceof Tt&&e.status===404}async function C(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(vt(e),{...n,headers:r});if(!i.ok)throw new Tt(Dt(await i.json().catch(()=>({})))??i.statusText,i.status);let a=await i.json();return wt(),t(a)}function Dt(e){if(Ot(e))return typeof e.error==`string`?e.error:void 0}function Ot(e){return typeof e==`object`&&!!e}var kt={pluginLifecycle:`plugins.lifecycle`},At=1e3,jt=32*1024,Mt=8*1024,Nt=1e3,Pt=4e3,Ft=1e3,It=8e3,Lt=4e3,Rt=1e4,zt={working:`core:working`,terminal:`core:terminal`,unread:`core:unread`};function Bt(e){if(!Ut(e))return;let t=e.epochId,n=e.revision,r=e.generatedAt,i=Vt(e.machine),a=Vt(e.unattributed),o=Ht(e.projects),s=Ht(e.workspaces);if(!(typeof t!=`string`||t===``)&&!(typeof n!=`number`||!Number.isFinite(n))&&!(typeof r!=`string`||r===``)&&!(i===void 0||a===void 0)&&!(o===void 0||s===void 0))return{epochId:t,revision:n,machine:i,projects:o,workspaces:s,unattributed:a,generatedAt:r}}function Vt(e){if(!Ut(e))return;let t=new Map;for(let[n,r]of Object.entries(e))typeof r==`boolean`&&t.set(n,r);return Object.fromEntries(t)}function Ht(e){if(!Ut(e))return;let t=new Map;for(let[n,r]of Object.entries(e)){let e=Vt(r);e!==void 0&&t.set(n,e)}return Object.fromEntries(t)}function Ut(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Wt=Object.values(kt),Gt=new Set(Wt);kt.pluginLifecycle,kt.pluginLifecycle;function Kt(e){return typeof e==`string`&&Gt.has(e)}function qt(e,t){return e?.capabilities?.includes(t)===!0}function Jt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Kt)}function Yt(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Xt(n))continue;let e=n.source,r=n.name,i=n.replacement;e!==`environment`&&e!==`config`||typeof r!=`string`||r===``||i!==void 0&&(typeof i!=`string`||i===``)||t.push({source:e,name:r,...i===void 0?{}:{replacement:i}})}return t}function Xt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Zt=/^[a-z][a-z0-9.-]*$/u,Qt=new Set([`core`,`themes`]),$t=`machine.`;function en(e){return Zt.test(e)}function tn(e){return Qt.has(e)||e.startsWith($t)}var nn=Object.freeze({showSafeStart:`pi-web plugins safe-start show`,bundledOnly:`pi-web plugins safe-start set bundled-only --restart`,noServerPlugins:`pi-web plugins safe-start set none --restart`,clearSafeStart:`pi-web plugins safe-start clear --restart`});function rn(e){if(!en(e))throw Error(`Invalid PI WEB plugin id: ${e}`);return`pi-web plugins disable ${e} --restart`}function w(e){return typeof e==`object`&&!!e}function T(e){if(!w(e))throw Error(`Expected object response`);return e}function E(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function D(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function O(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function k(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function A(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function an(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function on(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function sn(e){let t=T(e);return{messages:an(t.messages),start:O(t,`start`),total:O(t,`total`)}}function cn(e){let t=T(e);return A(ln)(t.machines)}function ln(e){let t=T(e),n=pn(t,`kind`),r=D(t,`baseUrl`),i=mn(t,`status`),a=D(t,`statusMessage`);return{id:E(t,`id`),name:E(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:E(t,`createdAt`),updatedAt:E(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function un(e){let t=T(e),n=mn(t,`status`),r=D(t,`error`);return{machineId:E(t,`machineId`),ok:k(t,`ok`),checkedAt:E(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:va(t.web)},...t.sessiond===void 0?{}:{sessiond:va(t.sessiond)},...r===void 0?{}:{error:r}}}function dn(e){let t=T(e),n=D(t,`error`);return{machineId:E(t,`machineId`),ok:k(t,`ok`),checkedAt:E(t,`checkedAt`),...M(`packageName`,D(t,`packageName`)),...M(`generatedAt`,D(t,`generatedAt`)),...t.components===void 0?{}:{components:ga(t.components)},...t.capabilities===void 0?{}:{capabilities:wa(t.capabilities)},...t.deprecatedAgentInputs===void 0?{}:{deprecatedAgentInputs:fn(t.deprecatedAgentInputs)},...n===void 0?{}:{error:n}}}function fn(e){let t=Yt(e);if(t===void 0)throw Error(`Invalid PI WEB deprecated agent inputs`);return t}function pn(e,t){let n=E(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function mn(e,t){let n=D(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 hn(e){let t=T(e);return{id:E(t,`id`),name:E(t,`name`),path:E(t,`path`),createdAt:E(t,`createdAt`)}}function gn(e){let t=T(e);return Object.freeze({id:E(t,`id`),projectId:E(t,`projectId`),path:E(t,`path`),label:E(t,`label`),isMain:k(t,`isMain`),...M(`provider`,Sn(t.provider)),...M(`removal`,Cn(t.removal)),effectiveConfig:En(t.effectiveConfig)})}function _n(e){let t=T(e),n=vn(t.status),r=E(t,`projectId`),i=D(t,`ownerPluginId`);if(n===`provider`&&i===void 0)throw Error(`Provider workspace resolution is missing ownerPluginId`);if(n===`folder`&&i!==void 0)throw Error(`Folder workspace resolution must not include ownerPluginId`);let a=A(gn)(t.workspaces);if(a.length===0||a.some(e=>e.projectId!==r))throw Error(`Workspace resolution contains invalid project workspaces`);let o=A(yn)(t.diagnostics);return Object.freeze({status:n,projectId:r,...i===void 0?{}:{ownerPluginId:i},workspaces:Object.freeze(a),diagnostics:Object.freeze(o)})}function vn(e){if(e===`provider`||e===`folder`||e===`degraded`)return e;throw Error(`Invalid workspace provider resolution status`)}function yn(e){let t=T(e),n=D(t,`pluginId`),r=t.pluginIds===void 0?void 0:on(t.pluginIds,`pluginIds`);return Object.freeze({code:bn(t.code),message:E(t,`message`),tier:xn(t.tier),...n===void 0?{}:{pluginId:n},...r===void 0?{}:{pluginIds:Object.freeze(r)}})}function bn(e){if(e===`probe-failed`||e===`claim-conflict`||e===`list-failed`)return e;throw Error(`Invalid workspace provider diagnostic code`)}function xn(e){if(e===`primary`||e===`fallback`)return e;throw Error(`Invalid workspace provider diagnostic tier`)}function Sn(e){if(e===void 0)return;if(!w(e)||Array.isArray(e))throw Error(`Invalid workspace provider field`);let t=e.capabilities;if(!w(t)||Array.isArray(t))throw Error(`Invalid workspace provider capabilities field`);let n=e.metadata;return Object.freeze({pluginId:E(e,`pluginId`),capabilities:Object.freeze({request:k(t,`request`),remove:k(t,`remove`)}),...M(`metadata`,n===void 0?void 0:wn(n,`workspace provider metadata`))})}function Cn(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid workspace removal field`);return Object.freeze({actionLabel:j(e,`actionLabel`),confirmation:j(e,`confirmation`),precondition:j(e,`precondition`)})}}function wn(e,t){if(!w(e)||Array.isArray(e))throw Error(`Invalid ${t} field`);return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Tn(n,t)])))}function Tn(e,t){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(Array.isArray(e))return Object.freeze(e.map(e=>Tn(e,t)));if(w(e))return wn(e,t);throw Error(`Invalid ${t} field`)}function En(e){if(!w(e)||Array.isArray(e))throw Error(`Expected workspace effectiveConfig field`);let t=Ki(e.uploads);return Object.freeze({...M(`uploads`,t===void 0?void 0:Object.freeze({...t}))})}function Dn(e){let t=T(e),n=D(t,`name`),r=fa(t.persisted,`persisted`),i=D(t,`parentSessionPath`),a=D(t,`archivedAt`);return{id:E(t,`id`),path:E(t,`path`),cwd:E(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:E(t,`created`),modified:E(t,`modified`),messageCount:O(t,`messageCount`),firstMessage:E(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a}}}function On(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function kn(e){if(e!==void 0)return{id:E(T(e),`id`)}}function An(e){let t=T(e),n=kn(t.dismiss);return{severity:On(t.severity),message:E(t,`message`),...M(`source`,D(t,`source`)),...M(`path`,D(t,`path`)),...n===void 0?{}:{dismiss:n}}}function jn(e){return e===void 0?{}:{warnings:A(An)(e)}}function Mn(e){let t=T(e);return{value:xr(t,`value`,128),label:xr(t,`label`,Nt),...M(`detail`,Sr(t,`detail`,Nt))}}function Nn(e){let t=T(e),n=Nr(t.options,Mn,12,`options`);Un(n.map(e=>e.value),`ask option value`);let r=fa(t.multiple,`multiple`);return{id:xr(t,`id`,128),question:xr(t,`question`,Nt),...M(`detail`,Sr(t,`detail`,Nt)),options:n,...r===void 0?{}:{multiple:r}}}function Pn(e){let t=T(e),n=Nr(t.questions,Nn,20,`questions`);if(n.length===0)throw Error(`Pending ask has no questions`);return Un(n.map(e=>e.id),`ask question id`),{askId:xr(t,`askId`,128),askedAt:j(t,`askedAt`),questions:n}}function Fn(e){return e===void 0?{}:{pendingAsk:Pn(e)}}function In(e){let t=T(e);if(t.type!==`ask.opened`)throw Error(`Invalid ask opened event type`);return{type:`ask.opened`,ask:Pn(t.ask)}}function Ln(e){let t=T(e);if(t.type!==`ask.closed`)throw Error(`Invalid ask closed event type`);return{type:`ask.closed`,askId:xr(t,`askId`,128),reason:Rn(t.reason)}}function Rn(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function zn(e){let t=T(e),n=Nn(t.question),r=Nr(t.values,Pr,12,`values`),i=new Set(n.options.map(e=>e.value));if(r.some(e=>!i.has(e)))throw Error(`Ask answer selected an option the question never offered`);let a=Sr(t,`otherText`,Pt),o=k(t,`answered`);if(o!==(r.length>0||a!==void 0))throw Error(`Ask answer contradicts its answered flag`);return{question:n,answered:o,values:r,...a===void 0?{}:{otherText:a}}}function Bn(e){let t=T(e),n=Nr(t.questions,zn,20,`questions`),r=Fr(t,`answeredCount`),i=on(t.unansweredIds,`unansweredIds`),a=n.filter(e=>!e.answered).map(e=>e.question.id);if(r!==n.length-a.length)throw Error(`Ask outcome answered count mismatch`);if(i.length!==a.length||i.some((e,t)=>e!==a[t]))throw Error(`Ask outcome unanswered ids mismatch`);return{askId:xr(t,`askId`,128),reason:Rn(t.reason),askedAt:j(t,`askedAt`),closedAt:j(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:j(t,`summary`)}}function Vn(e){let t=T(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid ask close result`);let r=t.outcome===void 0?void 0:Bn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Ask close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:er(t.sessionStatus)}}function Hn(e){let t=T(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid dialog close result`);let r=t.outcome===void 0?void 0:Qn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Dialog close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:er(t.sessionStatus)}}function Un(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function Wn(e){if(e!==`confirm`&&e!==`select`&&e!==`input`)throw Error(`Invalid extension dialog kind`);return e}function Gn(e){if(e!==`answered`&&e!==`cancelled`&&e!==`timeout`&&e!==`aborted`&&e!==`session-ended`)throw Error(`Invalid extension dialog close reason`);return e}function Kn(e){if(typeof e==`boolean`||typeof e==`string`&&e.length<=4e3)return e;throw Error(`Invalid extension dialog answer`)}function qn(e){let t=Pr(e);if(t.length>1e3)throw Error(`String field exceeds limit: option`);return t}function Jn(e){let t=T(e),n=Wn(t.kind),r=t.options===void 0?void 0:Nr(t.options,qn,24,`options`);if(r!==void 0&&Un(r,`dialog option`),n===`select`&&(r===void 0||r.length===0))throw Error(`Select dialog has no options`);return{dialogId:xr(t,`dialogId`,128),kind:n,title:xr(t,`title`,It),...M(`message`,Sr(t,`message`,It)),...r===void 0?{}:{options:r},...M(`placeholder`,Sr(t,`placeholder`,Ft)),askedAt:j(t,`askedAt`),...M(`timeoutAt`,$n(t,`timeoutAt`)),runScoped:k(t,`runScoped`)}}function Yn(e){if(e===void 0)return{};let t=A(Jn)(e);return Un(t.map(e=>e.dialogId),`dialog id`),{pendingDialogs:t}}function Xn(e){let t=T(e);if(t.type!==`dialog.opened`)throw Error(`Invalid dialog opened event type`);return{type:`dialog.opened`,dialog:Jn(t.dialog)}}function Zn(e){let t=T(e);if(t.type!==`dialog.closed`)throw Error(`Invalid dialog closed event type`);let n=Gn(t.reason),r=t.answer===void 0?void 0:Kn(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog closed event answer mismatch`);return{type:`dialog.closed`,dialogId:xr(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r}}}function Qn(e){let t=T(e),n=Gn(t.reason),r=t.answer===void 0?void 0:Kn(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog outcome answer mismatch`);return{dialogId:xr(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r},askedAt:j(t,`askedAt`),closedAt:j(t,`closedAt`)}}function $n(e,t){let n=D(e,t);if(n!==void 0){if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}}function er(e){let t=T(e);return{sessionId:E(t,`sessionId`),...M(`persisted`,fa(t.persisted,`persisted`)),isStreaming:k(t,`isStreaming`),isCompacting:k(t,`isCompacting`),isBashRunning:k(t,`isBashRunning`),pendingMessageCount:O(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:A(Jr)(t.queuedMessages),...M(`messageCount`,Ya(t,`messageCount`)),tokens:Yr(t.tokens),cost:O(t,`cost`),...Zr(t.model),..._i(t.contextUsage),...M(`thinkingLevel`,D(t,`thinkingLevel`)),...jn(t.warnings),...Fn(t.pendingAsk),...Yn(t.pendingDialogs)}}function tr(e){let t=T(e);return{seq:O(t,`seq`),partial:t.partial??null}}function nr(e){let t=T(e),n=t.subtasks===void 0?[]:A(nr)(t.subtasks);return{id:E(t,`id`),title:E(t,`title`),status:E(t,`status`),...M(`verificationContract`,D(t,`verificationContract`)),...n.length===0?{}:{subtasks:n}}}function rr(e){let t=T(e);return{id:E(t,`id`),objective:E(t,`objective`),status:E(t,`status`),path:E(t,`path`),sisyphus:k(t,`sisyphus`),autoContinue:k(t,`autoContinue`),...M(`createdAt`,D(t,`createdAt`)),...M(`updatedAt`,D(t,`updatedAt`)),...M(`currentTaskId`,D(t,`currentTaskId`)),...M(`stopReason`,D(t,`stopReason`)),...M(`pauseReason`,D(t,`pauseReason`)),...M(`verificationContract`,D(t,`verificationContract`)),...M(`tokensUsed`,Ya(t,`tokensUsed`)),...M(`activeSeconds`,Ya(t,`activeSeconds`)),tasks:A(nr)(t.tasks),completedTaskCount:O(t,`completedTaskCount`),totalTaskCount:O(t,`totalTaskCount`)}}function ir(e){let t=T(e);return{goals:A(rr)(t.goals),directory:E(t,`directory`),generatedAt:E(t,`generatedAt`)}}function ar(e){let t=T(e),n=A(er)(t.statuses),r=new Set;for(let e of n){if(r.has(e.sessionId))throw Error(`Duplicate session status in catalog`);r.add(e.sessionId)}return{statuses:n,generatedAt:E(t,`generatedAt`)}}function or(e){let t=T(e),n=Fr(t,`catalogRevision`),r=Nr(t.sessions,vr,At,`sessions`);if(yr(r),br(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:xr(t,`catalogId`,512),catalogRevision:n,sessions:r}}function sr(e){let t=T(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=xr(t,`sessionId`,512),r=xr(t,`cwd`,jt),i=Cr(t,`catalogRevision`),a=t.unread===null?null:vr(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:xr(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function cr(e){let t=T(e);if(t.type!==`session.startup`)throw Error(`Invalid session startup event type`);let n=D(t,`startupToken`);if(n===``)throw Error(`Expected non-empty string field: startupToken`);return{type:`session.startup`,...M(`startupToken`,n),activity:lr(t.activity)}}function lr(e){let t=T(e);return{sessionId:j(t,`sessionId`),phase:dr(t,`phase`),label:j(t,`label`),...M(`detail`,D(t,`detail`)),at:j(t,`at`),...M(`startup`,ur(t))}}function ur(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function dr(e,t){let n=E(e,t);if(n!==`active`&&n!==`idle`&&n!==`error`)throw Error(`Expected session activity phase field: ${t}`);return n}function fr(e){let t=T(e);switch(t.type){case`message.append`:return{type:`message.append`,message:mr(t,`message`),...M(`clientMessageId`,D(t,`clientMessageId`)),...t.echo===!0?{echo:!0}:{}};case`assistant.delta`:return{type:`assistant.delta`,text:E(t,`text`)};case`assistant.thinking.delta`:return{type:`assistant.thinking.delta`,text:E(t,`text`)};case`tool.start`:return{type:`tool.start`,toolName:E(t,`toolName`),toolCallId:E(t,`toolCallId`),summary:E(t,`summary`),...M(`args`,t.args)};case`tool.update`:return{type:`tool.update`,toolName:E(t,`toolName`),toolCallId:E(t,`toolCallId`),text:E(t,`text`),...M(`content`,t.content),...M(`details`,t.details)};case`tool.end`:return{type:`tool.end`,toolName:E(t,`toolName`),toolCallId:E(t,`toolCallId`),text:E(t,`text`),isError:k(t,`isError`),...M(`content`,t.content),...M(`details`,t.details)};case`shell.start`:return{type:`shell.start`,command:E(t,`command`),...M(`excludeFromContext`,fa(t.excludeFromContext,`excludeFromContext`))};case`shell.chunk`:return{type:`shell.chunk`,chunk:E(t,`chunk`)};case`shell.end`:return{type:`shell.end`,...M(`output`,D(t,`output`)),...M(`exitCode`,hr(t,`exitCode`)),...M(`cancelled`,fa(t.cancelled,`cancelled`)),...M(`truncated`,fa(t.truncated,`truncated`)),...M(`fullOutputPath`,D(t,`fullOutputPath`)),...M(`isError`,fa(t.isError,`isError`))};case`agent.start`:return{type:`agent.start`};case`agent.end`:return{type:`agent.end`};case`message.end`:return{type:`message.end`,...M(`message`,t.message)};case`status.update`:return{type:`status.update`,status:er(t.status)};case`activity.update`:return{type:`activity.update`,activity:lr(t.activity)};case`command.output`:return gr(t);case`session.error`:return{type:`session.error`,message:E(t,`message`)};case`session.name`:return _r(t);case`session.created`:return{type:`session.created`,session:Dn(t.session)};case`pi.event`:return{type:`pi.event`,eventType:E(t,`eventType`)};default:throw Error(`Unsupported session stream event type`)}}function pr(e){let t=T(e);switch(t.type){case`status.update`:return{type:`status.update`,status:er(t.status)};case`activity.update`:return{type:`activity.update`,activity:lr(t.activity)};case`session.name`:return _r(t);case`session.created`:return{type:`session.created`,session:Dn(t.session)};case`terminal.created`:return{type:`terminal.created`,terminal:Oi(t.terminal)};case`terminal.exited`:return{type:`terminal.exited`,terminal:Oi(t.terminal)};case`terminal.closed`:return{type:`terminal.closed`,terminalId:j(t,`terminalId`),cwd:j(t,`cwd`)};case`machine.status`:return{type:`machine.status`,status:Mi(t.status)};default:throw Error(`Unsupported realtime stream event type`)}}function mr(e,t){let n=e[t];if(n===void 0)throw Error(`Expected field: ${t}`);return n}function hr(e,t){let n=e[t];if(n!==void 0){if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected optional number|null field: ${t}`);return n}}function gr(e){let t=E(e,`level`);if(t!==`info`&&t!==`success`&&t!==`error`)throw Error(`Invalid command output level`);return{type:`command.output`,level:t,message:E(e,`message`)}}function _r(e){return{type:`session.name`,sessionId:j(e,`sessionId`),...M(`name`,D(e,`name`))}}function vr(e){let t=T(e),n=xr(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:xr(t,`sessionId`,512),cwd:xr(t,`cwd`,jt),completionOrder:Cr(t,`completionOrder`),completedAt:n}}function yr(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 br(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 xr(e,t,n){let r=j(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Sr(e,t,n){let r=D(e,t);if(r!==void 0){if(r===``)throw Error(`Expected non-empty string field: ${t}`);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}}function Cr(e,t){let n=Fr(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function wr(e){let t=T(e),n=Er(t.summary),r=Nr(t.notifications,Dr,100,`notifications`);if(Ir(r),Lr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==zr(r))throw Error(`Notification snapshot severity mismatch`);let i=Or(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:j(t,`daemonInstanceId`),catalogRevision:Fr(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Tr(e){let t=T(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=Er(t.summary),r=Or(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=kr(t.delta);if(i.kind===`cleared`&&!Rr(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:j(t,`daemonInstanceId`),catalogRevision:Fr(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function Er(e){let t=T(e),n=Fr(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Fr(t,`discardedCount`),i=jr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:j(t,`sessionId`),cwd:j(t,`cwd`),inboxRevision:Fr(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Dr(e){let t=T(e),n=E(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=E(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=Fr(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:j(t,`id`),message:n,truncated:k(t,`truncated`),severity:Ar(t.severity),receivedAt:r,order:i}}function Or(e){let t=T(e);return{order:Fr(t,`order`),overflowWatermark:Fr(t,`overflowWatermark`)}}function kr(e){let t=T(e);switch(t.kind){case`added`:{let e=D(t,`evictedNotificationId`);return{kind:`added`,notification:Dr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=Nr(t.notificationIds,Pr,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:Mr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function Ar(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function jr(e){return e===void 0?void 0:Ar(e)}function Mr(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 Nr(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 Pr(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function j(e,t){let n=E(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function Fr(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 Ir(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 Lr(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 Rr(e){return e.retainedCount===0&&e.discardedCount===0}function zr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Br(e){let t=T(e),n=t.skippedBusySessionIds===void 0?void 0:on(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:E(t,`generatedAt`),thresholds:Gr(t.thresholds),projects:A(Kr)(t.projects),totals:qr(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Vr(e){let t=T(e);return{...Br(t),archivedSessionIds:on(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:on(t.deletedSessionIds,`deletedSessionIds`)}}function Hr(e){let t=T(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:on(t.archivedSessionIds,`archivedSessionIds`),failures:A(Wr)(t.failures),generatedAt:E(t,`generatedAt`)}}function Ur(e){let t=T(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:on(t.deletedSessionIds,`deletedSessionIds`),failures:A(Wr)(t.failures),generatedAt:E(t,`generatedAt`)}}function Wr(e){let t=T(e);return{sessionId:E(t,`sessionId`),error:E(t,`error`)}}function Gr(e){let t=T(e);return{...M(`archiveIdleDays`,Ya(t,`archiveIdleDays`)),...M(`deleteArchivedDays`,Ya(t,`deleteArchivedDays`))}}function Kr(e){let t=T(e);return{cwd:E(t,`cwd`),archiveCount:O(t,`archiveCount`),deleteCount:O(t,`deleteCount`)}}function qr(e){let t=T(e);return{archiveCount:O(t,`archiveCount`),deleteCount:O(t,`deleteCount`)}}function Jr(e){let t=T(e),n=E(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:E(t,`text`),...M(`clientMessageId`,D(t,`clientMessageId`))}}function Yr(e){let t=T(e);return{input:O(t,`input`),output:O(t,`output`),cacheRead:O(t,`cacheRead`),cacheWrite:O(t,`cacheWrite`),total:O(t,`total`)}}function Xr(e){let t=T(e);return{...M(`provider`,D(t,`provider`)),...M(`id`,D(t,`id`)),...M(`name`,D(t,`name`)),...M(`contextWindow`,Ya(t,`contextWindow`)),...M(`reasoning`,t.reasoning)}}function Zr(e){return e===void 0?{}:{model:Xr(e)}}function Qr(e){let t=T(e);return{models:A(Xr)(t.models)}}function $r(e){let t=T(e);return{provider:E(t,`provider`),id:E(t,`id`),...M(`name`,D(t,`name`)),...M(`contextWindow`,Ya(t,`contextWindow`)),...M(`reasoning`,t.reasoning),enabled:k(t,`enabled`)}}function ei(e){let t=T(e);return{models:A($r)(t.models)}}function ti(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function ni(e){let t=T(e);return{levels:A(ti)(t.levels)}}function ri(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function ii(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 ai(e){let t=T(e),n=t.source===void 0?void 0:ii(t.source);return{configured:k(t,`configured`),...M(`source`,n),...M(`label`,D(t,`label`))}}function oi(e){let t=T(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:E(t,`id`),name:E(t,`name`),authType:ri(t.authType),status:ai(t.status),...n===void 0?{}:{loginFlow:n}}}function si(e){let t=T(e);return{providers:A(oi)(t.providers)}}function ci(e){let t=T(e);return{flowId:E(t,`flowId`),providerId:E(t,`providerId`),providerName:E(t,`providerName`),status:li(t.status),progress:A(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...M(`error`,D(t,`error`)),...M(`auth`,ui(t.auth)),...M(`prompt`,fi(t.prompt)),...M(`select`,mi(t.select)),...M(`info`,hi(t.info))}}function li(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function ui(e){if(e===void 0)return;let t=T(e);return{url:E(t,`url`),...M(`instructions`,D(t,`instructions`)),...M(`deviceCode`,di(t.deviceCode))}}function di(e){if(e===void 0)return;let t=T(e);return{userCode:E(t,`userCode`),...M(`intervalSeconds`,Ya(t,`intervalSeconds`)),...M(`expiresInSeconds`,Ya(t,`expiresInSeconds`))}}function fi(e){if(e===void 0)return;let t=T(e);return{requestId:E(t,`requestId`),message:E(t,`message`),promptType:pi(t.promptType),...M(`placeholder`,D(t,`placeholder`)),...M(`allowEmpty`,Ja(t,`allowEmpty`))}}function pi(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function mi(e){if(e===void 0)return;let t=T(e);return{requestId:E(t,`requestId`),message:E(t,`message`),options:A(Ia)(t.options)}}function hi(e){if(e!==void 0)return A(e=>{let t=T(e);return{message:E(t,`message`),...M(`links`,t.links===void 0?void 0:A(gi)(t.links))}})(e)}function gi(e){let t=T(e);return{url:E(t,`url`),...M(`label`,D(t,`label`))}}function _i(e){if(e===void 0)return{};let t=T(e);return{contextUsage:{tokens:Xa(t,`tokens`),contextWindow:O(t,`contextWindow`),percent:Xa(t,`percent`)}}}function vi(e){let t=T(e),n=E(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:E(t,`name`),source:n,...M(`description`,D(t,`description`))}}function yi(e){let t=T(e),n=E(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:E(t,`path`),kind:n}}function bi(e){let t=T(e);return{path:E(t,`path`),entries:A(xi)(t.entries),scannedAt:E(t,`scannedAt`),truncated:k(t,`truncated`)}}function xi(e){let t=T(e),n=E(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:E(t,`name`),path:E(t,`path`),type:n,...M(`size`,Ya(t,`size`)),...M(`modifiedAt`,D(t,`modifiedAt`))}}function Si(e){let t=T(e),n=E(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:E(t,`path`),...M(`language`,D(t,`language`)),...M(`mediaType`,Ei(t.mediaType)),...M(`mimeType`,D(t,`mimeType`)),encoding:n,size:O(t,`size`),modifiedAt:E(t,`modifiedAt`),content:E(t,`content`),truncated:k(t,`truncated`),binary:k(t,`binary`)}}function Ci(e){let t=T(e);return{path:E(t,`path`),size:O(t,`size`),modifiedAt:E(t,`modifiedAt`),created:k(t,`created`)}}function wi(e){let t=T(e);return{path:E(t,`path`),existed:k(t,`existed`)}}function Ti(e){let t=T(e);return{fromPath:E(t,`fromPath`),toPath:E(t,`toPath`),size:O(t,`size`),modifiedAt:E(t,`modifiedAt`)}}function Ei(e){if(e!==void 0){if(e!==`image`&&e!==`html`&&e!==`pdf`&&e!==`markdown`)throw Error(`Invalid file media type`);return e}}function Di(e){let t=T(e),n=t.decision;if(n!==!0&&n!==!1&&n!==null)throw Error(`Invalid workspace trust decision`);return{path:E(t,`path`),decision:n,trusted:k(t,`trusted`)}}function Oi(e){let t=T(e);return{id:E(t,`id`),cwd:E(t,`cwd`),name:E(t,`name`),createdAt:E(t,`createdAt`),exited:k(t,`exited`),...M(`exitCode`,Ya(t,`exitCode`)),...M(`commandRunId`,D(t,`commandRunId`))}}function ki(e){let t=T(e);return{id:E(t,`id`),origin:E(t,`origin`),projectId:E(t,`projectId`),workspaceId:E(t,`workspaceId`),terminalId:E(t,`terminalId`),title:E(t,`title`),command:E(t,`command`),status:Ai(t.status),...M(`exitCode`,Ya(t,`exitCode`)),createdAt:E(t,`createdAt`),...M(`startedAt`,D(t,`startedAt`)),...M(`completedAt`,D(t,`completedAt`)),metadata:ji(t.metadata,`metadata`)}}function Ai(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function ji(e,t){let n=T(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 Mi(e){let t=Bt(e);if(t===void 0)throw Error(`Expected machine status snapshot`);return t}function Ni(e){let t=T(e),n=t.enabled===!0,r=typeof t.disabledReason==`string`?t.disabledReason:void 0,i=typeof t.latest==`string`?t.latest:void 0,a=typeof t.branch==`string`?t.branch:void 0;return n?{enabled:!0,current:E(t,`current`),latest:i,available:t.available===!0,branch:a,checkedAt:E(t,`checkedAt`)}:{enabled:!1,current:``,latest:i,available:!1,branch:a,checkedAt:E(t,`checkedAt`),...r===void 0?{}:{disabledReason:r}}}function Pi(e){let t=T(e);return{goalId:E(t,`goalId`),archivedPath:typeof t.archivedPath==`string`?t.archivedPath:``,alreadyArchived:t.alreadyArchived===!0,agentMayRecreate:t.agentMayRecreate===!0}}function Fi(e){let t=T(e);return{hub:Li(t.hub),machines:A(Ri)(t.machines)}}function Ii(e){let t=T(e),n=E(t,`operation`);if(n!==`restart`&&n!==`update`)throw Error(`Invalid fleet operation`);return{operation:n,hub:Li(t.hub),outcomes:A(zi)(t.outcomes)}}function Li(e){let t=T(e);return{machineId:E(t,`machineId`),name:E(t,`name`)}}function Ri(e){let t=T(e),n=E(t,`kind`);if(n!==`local`&&n!==`remote`)throw Error(`Invalid machine kind`);return{...Li(e),kind:n,online:t.online===!0,...M(`version`,D(t,`version`)),...M(`piVersion`,D(t,`piVersion`)),...M(`error`,D(t,`error`))}}function zi(e){let t=T(e);return{...Li(e),started:t.started===!0,...M(`error`,D(t,`error`))}}function Bi(e){let t=T(e);return{path:E(t,`path`),exists:k(t,`exists`),config:Vi(t.config),effectiveConfig:Vi(t.effectiveConfig),envOverrides:Zi(t.envOverrides)}}function Vi(e){let t=T(e);return{...M(`host`,D(t,`host`)),...M(`port`,Ya(t,`port`)),...M(`allowedHosts`,Ui(t.allowedHosts)),...M(`shortcuts`,Yi(t.shortcuts)),...M(`plugins`,Xi(t.plugins)),...M(`pathAccess`,Wi(t.pathAccess)),...M(`uploads`,Ki(t.uploads)),...M(`maxUploadBytes`,Ya(t,`maxUploadBytes`)),...M(`agent`,Hi(t.agent)),...M(`spawnSessions`,Ja(t,`spawnSessions`)),...M(`subsessions`,Ja(t,`subsessions`)),...M(`askUser`,Ja(t,`askUser`))}}function Hi(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB agent field`);return{...M(`command`,D(e,`command`)),...M(`dir`,D(e,`dir`))}}}function Ui(e){if(e!==void 0){if(e===!0)return!0;if(qi(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function Wi(e){if(e===void 0)return;if(!w(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...M(`allowedPaths`,Gi(t,`pathAccess.allowedPaths`))}}function Gi(e,t){if(e!==void 0){if(Ji(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function Ki(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB uploads field`);return{...M(`defaultFolder`,D(e,`defaultFolder`))}}}function qi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Ji(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Yi(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEB shortcut field`);return[e,t]}))}}function Xi(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!w(t)||Array.isArray(t))throw Error(`Invalid PI WEB plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEB plugin enabled field`);let r=t.settings;if(r!==void 0&&(!w(r)||Array.isArray(r)))throw Error(`Invalid PI WEB plugin settings field`);return[e,t]}))}}function Zi(e){let t=T(e);return{host:k(t,`host`),port:k(t,`port`),allowedHosts:k(t,`allowedHosts`),spawnSessions:k(t,`spawnSessions`),subsessions:k(t,`subsessions`),askUser:k(t,`askUser`)}}function Qi(e){let t=T(e);return{packages:A(ea)(t.packages)}}function $i(e){let t=T(e),n=D(t,`source`),r=t.scope===void 0?void 0:ta(t.scope),i=fa(t.removed,`removed`);return{action:na(t.action),...M(`source`,n),...M(`scope`,r),...M(`removed`,i),packages:A(ea)(t.packages)}}function ea(e){let t=T(e);return{source:E(t,`source`),scope:ta(t.scope),filtered:k(t,`filtered`),...M(`installedPath`,D(t,`installedPath`))}}function ta(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function na(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function ra(e){let t=T(e),n=A(ia)(t.plugins);if(t.lifecycleVersion===void 0)return{lifecycleVersion:1,plugins:n,diagnostics:[],serverRuntime:{status:`incompatible`,restartRequired:!1,message:`PI WEB does not support plugin lifecycle diagnostics. Update and restart PI WEB, then try again.`,recovery:ua()}};if(t.lifecycleVersion!==1)throw Error(`Unsupported PI WEB plugin lifecycle version`);return{lifecycleVersion:1,plugins:n,diagnostics:A(sa)(t.diagnostics),serverRuntime:ca(t.serverRuntime)}}function ia(e){let t=T(e),n=E(t,`id`),r=t.server===void 0?void 0:aa(t.server,n);return{id:n,...M(`module`,D(t,`module`)),source:E(t,`source`),scope:da(t.scope),machineSpecific:fa(t.machineSpecific,`machineSpecific`)??!1,enabled:k(t,`enabled`),discovered:fa(t.discovered,`discovered`)??!0,conflict:fa(t.conflict,`conflict`)??!1,...r===void 0?{}:{server:r}}}function aa(e,t){let n=T(e),r=n.state,i=n.phase;if(r!==`active`&&r!==`failed`&&r!==`incompatible`&&r!==`disabled`&&r!==`missing`&&r!==`unknown`)throw Error(`Invalid PI WEB server plugin state`);if(i!==void 0&&i!==`import`&&i!==`activate`&&i!==`validate`&&i!==`start`&&i!==`health`&&i!==`stop`)throw Error(`Invalid PI WEB server plugin phase`);let a=n.health===void 0?void 0:oa(n.health),o=E(n,`disableCommand`);if(o!==rn(t))throw Error(`Invalid PI WEB server plugin recovery command`);return{state:r,...M(`desiredRevision`,D(n,`desiredRevision`)),...M(`activeRevision`,D(n,`activeRevision`)),...i===void 0?{}:{phase:i},...M(`message`,D(n,`message`)),...a===void 0?{}:{health:a},staleRevision:k(n,`staleRevision`),restartRequired:k(n,`restartRequired`),disableCommand:o}}function oa(e){let t=T(e),n=t.status;if(n!==`healthy`&&n!==`degraded`&&n!==`unhealthy`)throw Error(`Invalid PI WEB server plugin health status`);return{status:n,...M(`message`,D(t,`message`))}}function sa(e){let t=T(e),n=t.kind,r=t.snapshot;if(n!==`conflict`&&n!==`discovery`)throw Error(`Invalid PI WEB plugin diagnostic kind`);if(r!==`desired`&&r!==`active`)throw Error(`Invalid PI WEB plugin diagnostic snapshot`);return{kind:n,snapshot:r,source:E(t,`source`),message:E(t,`message`),...M(`pluginId`,D(t,`pluginId`))}}function ca(e){let t=T(e),n=t.status,r=t.safeStart,i=t.desiredSafeStart;if(n!==`available`&&n!==`unavailable`&&n!==`incompatible`)throw Error(`Invalid PI WEB server-plugin runtime status`);if(r!==void 0&&r!==`bundled-only`&&r!==`none`)throw Error(`Invalid PI WEB server-plugin safe-start state`);if(i!==void 0&&i!==`off`&&i!==`bundled-only`&&i!==`none`)throw Error(`Invalid desired PI WEB server-plugin safe-start state`);return{status:n,...r===void 0?{}:{safeStart:r},...i===void 0?{}:{desiredSafeStart:i},restartRequired:k(t,`restartRequired`),...M(`message`,D(t,`message`)),recovery:la(t.recovery)}}function la(e){let t=T(e),n={showSafeStart:E(t,`showSafeStart`),bundledOnly:E(t,`bundledOnly`),noServerPlugins:E(t,`noServerPlugins`),clearSafeStart:E(t,`clearSafeStart`)};if(n.showSafeStart!==nn.showSafeStart||n.bundledOnly!==nn.bundledOnly||n.noServerPlugins!==nn.noServerPlugins||n.clearSafeStart!==nn.clearSafeStart)throw Error(`Invalid PI WEB server plugin recovery commands`);return n}function ua(){return{...nn}}function da(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function fa(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function pa(e){let t=T(e);return{packageName:E(t,`packageName`),generatedAt:E(t,`generatedAt`),components:ha(t.components),release:ba(t.release),commands:xa(t.commands),messages:A(Sa)(t.messages)}}function ma(e){let t=T(e);return{packageName:E(t,`packageName`),generatedAt:E(t,`generatedAt`),components:ga(t.components),capabilities:wa(t.capabilities)}}function ha(e){let t=T(e);return{web:va(t.web),sessiond:va(t.sessiond)}}function ga(e){let t=T(e);return{web:_a(t.web),sessiond:_a(t.sessiond)}}function _a(e){let t=T(e);return{component:Ca(t.component),label:E(t,`label`),...M(`runtimeVersion`,D(t,`runtimeVersion`)),...M(`piVersion`,D(t,`piVersion`)),available:k(t,`available`),capabilities:wa(t.capabilities),...M(`error`,D(t,`error`))}}function va(e){let t=T(e);return{component:Ca(t.component),label:E(t,`label`),...M(`runtimeVersion`,D(t,`runtimeVersion`)),...M(`installedVersion`,D(t,`installedVersion`)),...M(`piVersion`,D(t,`piVersion`)),stale:k(t,`stale`),available:k(t,`available`),...M(`installation`,ya(t.installation)),...M(`error`,D(t,`error`))}}function ya(e){if(e===void 0)return;let t=T(e),n=E(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEB installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEB installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEB Docker mode`);return{kind:n,...M(`path`,D(t,`path`)),...M(`source`,D(t,`source`)),...r===void 0?{}:{scope:r},...M(`npmRoot`,D(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function ba(e){let t=T(e);return{packageName:E(t,`packageName`),...M(`latestVersion`,D(t,`latestVersion`)),updateAvailable:k(t,`updateAvailable`),...M(`checkedAt`,D(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...M(`error`,D(t,`error`))}}function xa(e){let t=T(e);return{...M(`update`,D(t,`update`)),...M(`restart`,D(t,`restart`)),...M(`restartWeb`,D(t,`restartWeb`)),...M(`restartSessiond`,D(t,`restartSessiond`)),...M(`status`,D(t,`status`))}}function Sa(e){let t=T(e);return{id:E(t,`id`),severity:Ta(t.severity),title:E(t,`title`),body:E(t,`body`),...M(`command`,D(t,`command`))}}function Ca(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function wa(e){let t=Jt(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function Ta(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function Ea(e){let t=T(e),n=E(t,`type`);if(n===`unsupported`)return{type:n,message:E(t,`message`)};if(n===`select`)return{type:n,requestId:E(t,`requestId`),title:E(t,`title`),options:A(Ia)(t.options)};if(n===`tree`)return{type:n,tree:Da(t.tree)};if(n===`done`)return{type:n,...M(`message`,D(t,`message`)),...La(t.session),...M(`promptDraft`,D(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Da(e){let t=T(e),n=A(Oa)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=Na(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:Fa(t.activePathIds,`activePathIds`)}}function Oa(e){let t=T(e);return{id:Pa(t,`id`),parentId:Na(t,`parentId`),kind:ka(t.kind),summary:E(t,`summary`),...M(`timestamp`,D(t,`timestamp`)),...M(`label`,D(t,`label`))}}function ka(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 Aa(e){let t=T(e),n=k(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){Ma(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 Ma(t,`aborted`,`session tree navigation result`),{cancelled:n,...M(`editorText`,D(t,`editorText`))}}function ja(e){let t=T(e),n=k(t,`cancelled`);return n?(Ma(t,`session`,`session tree fork cancellation result`),Ma(t,`promptDraft`,`session tree fork cancellation result`),{cancelled:n}):{cancelled:n,session:Dn(t.session),...M(`promptDraft`,D(t,`promptDraft`))}}function Ma(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function Na(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 Pa(e,t){let n=E(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function Fa(e,t){let n=on(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function Ia(e){let t=T(e);return{value:E(t,`value`),label:E(t,`label`),...M(`description`,D(t,`description`))}}function La(e){return e===void 0?{}:{session:Dn(e)}}function Ra(e){if(T(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function za(e){let t=T(e);return A(Ba)(t.attachments)}function Ba(e){let t=T(e);return{path:E(t,`path`),mimeType:E(t,`mimeType`),size:O(t,`size`)}}function Va(e){if(T(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function Ha(e){let t=T(e);if(t.aborted!==!0)throw Error(`Expected aborted response`);let n=t.discarded;return{aborted:!0,discarded:Array.isArray(n)?A(Jr)(n):[]}}function Ua(e){if(T(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function Wa(e){let t=T(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:on(t.sessionIds,`sessionIds`),r=Ya(t,`archivedCount`),i=Ya(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function Ga(e){if(T(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function Ka(e){if(T(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function qa(e){if(T(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function Ja(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function Ya(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function Xa(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 M(e,t){return t===void 0?{}:{[e]:t}}function Za(e){if(!w(e))return{runs:[]};let t=e.runs;if(!Array.isArray(t))return{runs:[]};let n=[];for(let e of t){if(!w(e))continue;let t=e.sessionId,r=e.cwd,i=e.interruptedAt;typeof t!=`string`||t===``||typeof r!=`string`||typeof i!=`string`||n.push({sessionId:t,cwd:r,interruptedAt:i})}return{runs:n}}function Qa(e){if(!w(e))return{subsessions:[],toolRuns:[]};let t=[],n=e.subsessions;if(Array.isArray(n))for(let e of n){if(!w(e))continue;let n=e.sessionId,r=e.cwd,i=e.status;typeof n!=`string`||n===``||typeof r==`string`&&(i!==`working`&&i!==`idle`&&i!==`error`&&i!==`unknown`||t.push({sessionId:n,cwd:r,status:i}))}return{subsessions:t,toolRuns:ro(e.toolRuns)}}function $a(e){let t=er(e);return{recalled:w(e)&&e.recalled===!0,status:t}}function eo(e){if(!w(e)||!Array.isArray(e.tasks))return[];let t=[];for(let n of e.tasks){if(!w(n))continue;let e=n.id,r=n.name,i=n.status;typeof e!=`string`||e===``||t.push({id:e,name:typeof r==`string`&&r!==``?r:e,command:typeof n.command==`string`?n.command:``,status:typeof i==`string`?i:`unknown`,...typeof n.startedAt==`string`?{startedAt:n.startedAt}:{},...typeof n.endedAt==`string`?{endedAt:n.endedAt}:{},...typeof n.durationMs==`number`?{durationMs:n.durationMs}:{},...typeof n.exitCode==`number`?{exitCode:n.exitCode}:{},bytesWritten:typeof n.bytesWritten==`number`?n.bytesWritten:0,hasOutput:n.hasOutput===!0})}return t}function to(e){if(!w(e))return``;let t=e.output;return typeof t==`string`?t:``}function no(e){if(!w(e))return``;let t=e.output;return typeof t==`string`?t:``}function ro(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!w(n))continue;let e=n.runId,r=n.agent,i=n.status,a=n.elapsedMs,o=n.startedAt;if(typeof e!=`string`||e===``||typeof r!=`string`||r===``||i!==`running`&&i!==`done`&&i!==`failed`&&i!==`lost`&&i!==`unknown`||typeof a!=`number`||typeof o!=`string`)continue;let s=n.lastActivity,c=n.task,l=n.model,u=n.toolCount;t.push({runId:e,agent:r,status:i,elapsedMs:a,startedAt:o,...typeof s==`string`&&s!==``?{lastActivity:s}:{},...typeof c==`string`&&c!==``?{task:c}:{},...typeof l==`string`&&l!==``?{model:l}:{},...typeof u==`number`?{toolCount:u}:{},hasOutput:n.hasOutput===!0})}return t}function io(e){return typeof e==`string`?e:e.id}function ao(e){return typeof e==`string`?void 0:e.cwd}function oo(e,t,n=`local`){let r=new URLSearchParams,i=ao(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(io(e))}/messages${a===``?``:`?${a}`}`}function so(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`),vt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function co(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),r?.download===!0&&i.set(`download`,`1`),`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`}function lo(e,t,n,r){return vt(co(e,t,n,r))}var N=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function uo(e,t=`local`){return`${N(t)}/sessions/${encodeURIComponent(e.id)}`}function P(e,t,n=`local`){return`${uo(e,n)}/${t}`}function fo(e,t,n=`local`){return`${P(e,t,n)}${po(e)}`}function po(e){return`?${new URLSearchParams({cwd:e.cwd}).toString()}`}function F(e,t={}){return JSON.stringify({cwd:e.cwd,...t})}function mo(e){return JSON.stringify({sessions:e.map(ho)})}function ho(e){return{id:e.id,cwd:e.cwd}}function go(e){return e===`local`?`api/pi-web/status`:`${N(e)}/pi-web/status`}var _o={piWebStatus:(e=`local`)=>C(go(e),pa),checkForUpdates:(e=`local`)=>C(`${go(e)}?refresh=1`,pa,{cache:`no-store`}),piWebRuntime:()=>C(`api/pi-web/runtime`,ma)},vo={machines:()=>C(`api/machines`,cn),addMachine:e=>C(`api/machines`,ln,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>C(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),updateMachine:(e,t)=>C(`api/machines/${encodeURIComponent(e)}`,ln,{method:`PATCH`,body:JSON.stringify(t)}),health:e=>C(`api/machines/${encodeURIComponent(e)}/health`,un),runtime:(e,t=!1)=>C(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,dn,t?{cache:`no-store`}:{})};function yo(e){return e===void 0?`api/config`:`${N(e)}/config`}function bo(e){return e===void 0?`api/plugins`:`${N(e)}/plugins`}var xo={config:e=>C(yo(e),Bi),saveConfig:(e,t)=>C(yo(t),Bi,{method:`PUT`,body:JSON.stringify({config:e})})};function So(e){let t=Bo(e)?e:{},n=t.started===!0,r=typeof t.error==`string`?t.error:void 0;return r===void 0?{started:n}:{started:n,error:r}}var Co={plugins:e=>C(bo(e),ra)},wo={status:()=>C(`api/pi-web/update/status`,Ni,{cache:`no-store`}),apply:()=>C(`api/pi-web/update/apply`,So,{method:`POST`,body:JSON.stringify({})})},To={report:()=>C(`api/pi-web/fleet`,Fi,{cache:`no-store`}),run:(e,t)=>C(`api/pi-web/fleet/run`,Ii,{method:`POST`,body:JSON.stringify({operation:e,...t===void 0?{}:{machineIds:t}})})};function Eo(e=``,t){let n=t===void 0?`api/pi-packages`:`${N(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Do={packages:e=>C(Eo(``,e),Qi),install:(e,t)=>{let n={source:e};return C(Eo(`install`,t),$i,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return C(Eo(`remove`,n),$i,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return C(Eo(`update`,t),$i,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},Oo={machineStatus:(e=`local`)=>C(`${N(e)}/status`,Mi)},ko={projects:(e=`local`)=>C(`${N(e)}/projects`,A(hn)),addProject:(e,t,n,r=`local`)=>C(`${N(r)}/projects`,hn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>C(`${N(t)}/projects/${encodeURIComponent(e)}`,Va,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>C(`${N(t)}/project-directories?q=${encodeURIComponent(e)}`,A(yi))};function Ao(e,t=`local`){return C(`${N(t)}/projects/${encodeURIComponent(e)}/workspaces`,t=>{let n=_n(t);if(n.projectId!==e)throw Error(`Workspace resolution did not match the requested project`);return n})}var jo={workspaceResolution:Ao,workspaces:async(e,t=`local`)=>[...(await Ao(e,t)).workspaces],deleteWorkspace:(e,t,n,r=`local`)=>{let i={precondition:n};return C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ki,{method:`DELETE`,body:JSON.stringify(i)})},archiveWorkspaceGoal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/goals/${encodeURIComponent(n)}/archive`,Pi,{method:`POST`,body:JSON.stringify({})}),workspaceGoals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/goals`,ir,{cache:`no-store`}),workspaceTree:(e,t,n=``,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,bi),workspaceFile:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,Si),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 C(`${N(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,Ci,{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 C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,wi,{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`),C(`${N(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,Ti,{method:`POST`})}},Mo={sessions:(e,t=`local`)=>C(`${N(t)}/sessions?cwd=${encodeURIComponent(e)}`,A(Dn)),unreadCatalog:(e=`local`)=>C(`${N(e)}/sessions/unread`,or,{cache:`no-store`}),statusCatalog:(e=`local`)=>C(`${N(e)}/sessions/statuses`,ar,{cache:`no-store`}),interruptedRuns:(e=`local`)=>C(`${N(e)}/sessions/interrupted`,Za,{cache:`no-store`}),subsessions:(e,t=`local`)=>C(`${P(e,`subsessions`,t)}?cwd=${encodeURIComponent(e.cwd)}`,Qa,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return C(P(e,`unread/acknowledge`,r),or,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>C(fo(e,`notifications`,t),wr),dismissNotification:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss`,r),wr,{method:`POST`,body:F(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss-all`,r),wr,{method:`POST`,body:F(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>C(`${N(t)}/sessions`,Dn,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup/preview`,Br,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup`,Vr,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/archive`,Hr,{method:`POST`,body:mo(e)}),deleteArchivedMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/delete-archived`,Ur,{method:`POST`,body:mo(e)}),messages:(e,t,n=`local`)=>C(oo(e,t,n),sn),status:(e,t=`local`)=>C(fo(e,`status`,t),er),streamSnapshot:(e,t=`local`)=>C(fo(e,`stream-snapshot`,t),tr),backgroundTasks:(e,t=`local`)=>C(`${P(e,`background-tasks`,t)}?cwd=${encodeURIComponent(e.cwd)}`,eo,{cache:`no-store`}),backgroundTaskOutput:(e,t,n=`local`)=>C(`${P(e,`background-tasks/${encodeURIComponent(t)}/output`,n)}?cwd=${encodeURIComponent(e.cwd)}`,to,{cache:`no-store`}),subagentRunOutput:(e,t,n=`local`)=>C(`${P(e,`subagent-runs/${encodeURIComponent(t)}/output`,n)}?cwd=${encodeURIComponent(e.cwd)}`,no,{cache:`no-store`}),clearQueue:(e,t=`local`)=>C(P(e,`queue/clear`,t),er,{method:`POST`,body:F(e)}),recallQueuedMessage:(e,t,n=`local`)=>C(P(e,`queue/clear`,n),$a,{method:`POST`,body:F(e,{text:t.text,kind:t.kind,...t.clientMessageId===void 0?{}:{clientMessageId:t.clientMessageId}})}),dismissWarning:(e,t,n=`local`)=>C(P(e,`warnings/dismiss`,n),er,{method:`POST`,body:F(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>C(P(e,`ask/submit`,r),Vn,{method:`POST`,body:F(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>C(P(e,`ask/cancel`,n),Vn,{method:`POST`,body:F(e,{askId:t})}),answerDialog:(e,t,n,r=`local`)=>C(P(e,`dialogs/answer`,r),Hn,{method:`POST`,body:F(e,{dialogId:t,value:n})}),cancelDialog:(e,t,n=`local`)=>C(P(e,`dialogs/cancel`,n),Hn,{method:`POST`,body:F(e,{dialogId:t})}),models:(e,t=`local`)=>C(fo(e,`models`,t),Qr),modelCatalog:(e,t=`local`)=>C(fo(e,`models/catalog`,t),ei),setModelEnabled:(e,t,n,r,i=`local`)=>C(P(e,`models/enabled`,i),ei,{method:`POST`,body:F(e,{provider:t,modelId:n,enabled:r})}),setModel:(e,t,n,r=`local`)=>C(P(e,`model`,r),er,{method:`POST`,body:F(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>C(P(e,`model/cycle`,n),er,{method:`POST`,body:F(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>C(fo(e,`thinking-levels`,t),ni),setThinkingLevel:(e,t,n=`local`)=>C(P(e,`thinking-level`,n),er,{method:`POST`,body:F(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>C(P(e,`thinking-level/cycle`,t),er,{method:`POST`,body:F(e)}),commands:(e,t=`local`)=>C(fo(e,`commands`,t),A(vi)),prompt:(e,t,n,r=`local`,i,a)=>C(P(e,`prompt`,r),Ra,{method:`POST`,body:F(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{},...a===void 0?{}:{clientMessageId:a}})}),saveAttachments:(e,t,n=`local`,r)=>C(P(e,`attachments`,n),za,{method:`POST`,body:F(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>C(P(e,`shell`,n),Ra,{method:`POST`,body:F(e,{text:t})}),runCommand:(e,t,n=`local`)=>C(P(e,`commands/run`,n),Ea,{method:`POST`,body:F(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>C(P(e,`commands/respond`,r),Ea,{method:`POST`,body:F(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>C(P(e,`tree/navigate`,n),Aa,{method:`POST`,body:F(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),forkTree:(e,t,n=`local`)=>Fo(e,t,n),abort:(e,t=`local`)=>C(P(e,`abort`,t),Ha,{method:`POST`,body:F(e)}),stop:(e,t=`local`)=>C(P(e,`stop`,t),Ua,{method:`POST`,body:F(e)}),archive:(e,t=`local`)=>C(P(e,`archive`,t),Wa,{method:`POST`,body:F(e)}),archiveWithDescendants:(e,t=`local`)=>C(P(e,`archive-tree`,t),Wa,{method:`POST`,body:F(e)}),restore:(e,t=`local`)=>C(P(e,`restore`,t),Ga,{method:`POST`,body:F(e)}),detachParent:(e,t=`local`)=>C(P(e,`detach-parent`,t),Ka,{method:`POST`,body:F(e)}),reloadSession:(e,t=`local`)=>C(P(e,`reload`,t),qa,{method:`POST`,body:F(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 C(`${N(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,si)},startInteractiveApiKeyLogin:(e,t=`local`)=>C(`${N(t)}/auth/api-key/interactive`,ci,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>C(`${N(t)}/auth/logout`,Ra,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>C(`${N(t)}/auth/oauth`,ci,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>C(`${N(t)}/auth/oauth/${encodeURIComponent(e)}`,ci),respondOAuthFlow:(e,t,n,r=`local`)=>C(`${N(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,ci,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>C(`${N(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ci,{method:`POST`})},No={terminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,A(Oi)),startTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Oi,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Va,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,Va,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,Oi,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ki,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs${Ro(e)}`,A(ki)),getCommandRun:(e,t=`local`)=>Lo(e,t),cancelCommandRun:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ki,{method:`POST`})},Po=class extends Error{constructor(){super(`Fork from the session tree is unavailable. Restart the session daemon to enable it.`),this.name=`SessionTreeForkUnavailableError`}};async function Fo(e,t,n){let r=await fetch(vt(P(e,`tree/fork`,n)),{method:`POST`,headers:{"content-type":`application/json`},body:F(e,{entryId:t.entryId,expectedLeafId:t.expectedLeafId})});if(!r.ok){let e=await r.json().catch(()=>({}));throw Io(r.status,e)?new Po:Error(zo(e)??r.statusText)}return ja(await r.json())}function Io(e,t){if(e!==404||!Bo(t)||t.statusCode!==404||t.error!==`Not Found`)return!1;let n=t.message;return typeof n==`string`&&/^Route POST:.*\/tree\/fork not found$/i.test(n)}async function Lo(e,t){let n=await fetch(vt(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(zo(e)??n.statusText)}return ki(await n.json())}}function Ro(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 zo(e){if(!Bo(e))return;let t=e.error;return typeof t==`string`?t:void 0}function Bo(e){return typeof e==`object`&&!!e}var Vo={files:(e,t)=>{let n=new URLSearchParams({q:e});return t.kind!==void 0&&n.set(`kind`,t.kind),t.mode!==void 0&&n.set(`mode`,t.mode),t.scope!==void 0&&n.set(`scope`,t.scope),C(`${N(t.machineId)}/projects/${encodeURIComponent(t.projectId)}/workspaces/${encodeURIComponent(t.workspaceId)}/files?${n.toString()}`,A(yi))}},Ho=(e,t,n)=>`${N(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/trust`,Uo=(e,t)=>{let n=new URLSearchParams({path:t});return`${N(e)}/projects/trust?${n.toString()}`},Wo={projectTrust:(e,t=`local`)=>C(Uo(t,e),Di),workspaceTrust:(e,t,n=`local`)=>C(Ho(n,e,t),Di),setWorkspaceTrust:(e,t,n,r=`local`)=>C(Ho(r,e,t),Di,{method:`PUT`,body:JSON.stringify({trusted:n})})},I={..._o,...vo,...xo,...Co,...Do,...ko,...jo,...Mo,...No,...Vo,...Wo},Go=256*1024,Ko=8*1024*1024,qo=266240,Jo=8392704,Yo=/^[a-z][a-z0-9.-]*$/u,Xo=64;function Zo(e){return e.length<=128&&Yo.test(e)}function Qo(e){if(!Zo(e))throw Error(`Plugin backend operation must match ${String(Yo)} and be at most 128 characters`);return e}function $o(e){if(typeof e!=`string`||e===``||e.length>512)throw Error(`Plugin backend revision must be a non-empty string of at most 512 characters`);return e}function es(e,t,n=Go){let r=rs(e,new Set,t,0);if(ns(JSON.stringify(r))>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);return r}function ts(e,t,n=Go){if(ns(e)>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);let r;try{r=JSON.parse(e)}catch(e){throw Error(`${t} must be valid JSON`,{cause:e})}return es(r,t,n)}function ns(e){return new TextEncoder().encode(e).byteLength}function rs(e,t,n,r){if(r>Xo)throw Error(`${n} exceeds the maximum JSON depth of ${String(Xo)}`);if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`${n} must contain only finite JSON numbers`);return e}if(Array.isArray(e)){if(t.has(e))throw Error(`${n} must not contain cycles`);t.add(e);let i=e.map(e=>rs(e,t,n,r+1));return t.delete(e),Object.freeze(i),i}if(!as(e))throw Error(`${n} must contain only JSON values`);if(t.has(e))throw Error(`${n} must not contain cycles`);t.add(e);let i={};for(let[a,o]of Object.entries(e))is(i,a,rs(o,t,n,r+1));return t.delete(e),Object.freeze(i)}function is(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function as(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function os(e,t){if(!en(e.pluginId))throw Error(`Invalid PI WEB plugin id: ${e.pluginId}`);if(e.machineId===``)throw Error(`Machine id is required`);if(e.projectId===``)throw Error(`Project id is required`);if(e.workspaceId===``)throw Error(`Workspace id is required`);let n=Qo(t);return`${e.machineId===`local`?`api`:`api/machines/${encodeURIComponent(e.machineId)}`}/plugin-backends/${encodeURIComponent(e.pluginId)}/projects/${encodeURIComponent(e.projectId)}/workspaces/${encodeURIComponent(e.workspaceId)}/${encodeURIComponent(n)}`}function ss(e,t,n){let r=os(e,t);return n===void 0?vt(r):vt(r,n)}async function cs(e,t,n){let r=$o(e.backendRevision),i=es(n,`Plugin backend request input`),a=JSON.stringify({revision:r,input:i});if(ns(a)>266240)throw Error(`Plugin backend request exceeds the ${String(qo)} byte wire limit`);let o;try{o=await fetch(ss(e,t),{method:`POST`,headers:{"content-type":`application/json`},body:a})}catch(e){throw Error(`Plugin backend request unavailable: ${fs(e)}`,{cause:e})}let s=await ls(o);if(!o.ok)throw Error(ds(s)??`Plugin backend request returned HTTP ${String(o.status)}`);return ts(s,`Plugin backend response`,Ko)}async function ls(e){let t=e.headers.get(`content-length`);if(t!==null&&/^\d+$/u.test(t)&&Number(t)>8392704)throw await e.body?.cancel(),Error(`Plugin backend response exceeds the ${String(Jo)} byte wire limit`);if(e.body===null){let t=await e.text();if(ns(t)>8392704)throw us();return t}let n=e.body.getReader(),r=new TextDecoder,i=0,a=``;try{let e=await n.read();for(;!e.done;){if(i+=e.value.byteLength,i>8392704)throw await n.cancel(),us();a+=r.decode(e.value,{stream:!0}),e=await n.read()}return a+r.decode()}finally{n.releaseLock()}}function us(){return Error(`Plugin backend response exceeds the ${String(Jo)} byte wire limit`)}function ds(e){try{let t=JSON.parse(e);return ps(t)&&typeof t.error==`string`?t.error:void 0}catch{return}}function fs(e){return e instanceof Error?e.message:String(e)}function ps(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ms(e,t=`local`){let n=`?${new URLSearchParams({cwd:e.cwd}).toString()}`;return new WebSocket(yt(`${_s(t)}/sessions/${encodeURIComponent(e.id)}/events${n}`))}function hs(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(yt(`${_s(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function gs(e=`local`){return new WebSocket(yt(`${_s(e)}/events`))}function _s(e){return`api/machines/${encodeURIComponent(e)}`}var vs=`.pi-web/uploads`,ys=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},bs=class extends Error{constructor(e,t){super(js(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function xs(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function Ss(e,t){return e.uploads?.defaultFolder??t}function Cs(e,t){let n=Ps(e,`upload destination`,{allowEmpty:!0}),r=Ps(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function ws(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`,so(e,t,n.path,Ds(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Os(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(Ci(Is(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Ls(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new ys(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function Ts(e,t,n,r={}){let i=r.destinationFolder??`.pi-web/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:Cs(i,e.name),loaded:0,total:e.size,percent:As(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(ks(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 ys;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=ws(e,t,{path:p.path,file:f},{...Es(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(Ns(e,c))throw e;let t=Ms(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 bs(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function Es(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 Ds(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Os(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:As(e.loaded,n),lengthComputable:e.lengthComputable}}function ks(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:As(i,r),done:n}}function As(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function js(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function Ms(e){return e instanceof Error?e.message:String(e)}function Ns(e,t){return t.requested||e instanceof ys}function Ps(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Fs(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 Fs(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Is(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Ls(e){let t=Rs(e);return zs(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Rs(e){try{return Is(e)}catch{return}}function zs(e){return typeof e==`object`&&!!e}function Bs(e,t){return{title:e,text:t,empty:t.trim()===``}}function Vs(){return{sessions:[],workspaceGoals:[],workspaceGoalsLoading:!1,clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,selectedFileLoadError:void 0,fileTreeStale:!1,selectedTerminalId:void 0,error:``}}function Hs(){return{machines:[],selfUpdate:void 0,selfUpdateApplying:!1,selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},machineStatusSnapshots:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,subagents:[],backgroundTasks:[],subagentRuns:[],activityOutput:void 0,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],workspaceGoals:[],workspaceGoalsLoading:!1,sessionStatuses:{},sessionActivities:{},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,selectedFileLoadError:void 0,fileTreeStale:!1,workspaceUploadBatches:{},activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:``}}function Us(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}var Ws=`machine.`;function Gs(e,t){if(e===``)throw Error(`Machine id is required`);if(!en(t))throw Error(`Invalid PI WEB plugin id: ${t}`);if(tn(t))throw Error(`Reserved PI WEB plugin id: ${t}`);return`${Ws}${Ks(e)}.${t}`}function Ks(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function qs(e,t){return`${e}:${t}`}function Js(e,t){return`${e}:${t}`}function L(e){return e.selectedMachine?.id??`local`}var Ys=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.applyStatus=n,this.authOperationGeneration=0,this.pollGeneration=0,this.api=r.api??I,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.advanceAuthOperation()}handleSlashCommand(e){let t=Qs(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){let t=this.advanceAuthOperation(),n=L(this.getState());if(e!==void 0&&e!==``){await this.openLoginProvider(e,n,t);return}this.setState({authDialog:{step:`method`,machineId:n}})}async chooseLoginMethod(e){let t=this.getState().authDialog;if(t?.step!==`method`)return;let n=this.authOperationGeneration,{machineId:r}=t;try{let{providers:i}=await this.api.authProviders({mode:`login`,authType:e,machineId:r});if(!this.isCurrentAuthOperation(n)||this.getState().authDialog!==t)return;this.setState({authDialog:{step:`providers`,mode:`login`,machineId:r,authType:e,providers:i}})}catch(e){this.isCurrentAuthOperation(n)&&this.getState().authDialog===t&&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));if(r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`)){let e=this.advanceAuthOperation();await this.startLoginFlow(r,n.machineId,e)}}async openLogout(e){let t=this.advanceAuthOperation(),n=L(this.getState());try{let{providers:r}=await this.api.authProviders({mode:`logout`,machineId:n});if(!this.isCurrentAuthOperation(t))return;if(e!==void 0&&e!==``){let i=r.find(t=>t.id===e);i===void 0?this.setState({error:`No stored credentials for ${e}`}):await this.logoutProviderOnMachine(i.id,n,t);return}this.setState({authDialog:{step:`logout`,machineId:n,providers:r}})}catch(e){this.isCurrentAuthOperation(t)&&this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog;if(t?.step!==`logout`)return;let n=this.advanceAuthOperation();await this.logoutProviderOnMachine(e,t.machineId,n)}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.authOperationGeneration,i=t.flow.flowId,a=n.requestId,o={flowId:i,requestId:a};if(Xs(this.inFlightResponse,o))return;let s=e??t.inputValue??``,c={...t};delete c.error,this.inFlightResponse=o,this.setState({authDialog:{...c,responding:!0}});try{let e=await this.api.respondOAuthFlow(i,a,s,t.machineId),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||Zs(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Zs(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}finally{Xs(this.inFlightResponse,o)&&(this.inFlightResponse=void 0)}}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.advanceAuthOperation(),this.setState({authDialog:void 0})}async openLoginProvider(e,t,n){try{let{providers:r}=await this.api.authProviders({mode:`login`,machineId:t});if(!this.isCurrentAuthOperation(n))return;let i=r.filter(t=>t.id===e);if(i.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(i.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,machineId:t,providers:i}});return}let a=i[0];if(a===void 0)return;(a.authType===`oauth`||a.loginFlow===`interactive`)&&await this.startLoginFlow(a,t,n)}catch(e){this.isCurrentAuthOperation(n)&&this.setState({error:String(e)})}}async logoutProviderOnMachine(e,t,n){if(this.isCurrentAuthOperation(n))try{if(await this.api.logoutProvider(e,t),!this.isCurrentAuthOperation(n))return;this.closeDialog(),this.refreshStatus(t)}catch(e){this.isCurrentAuthOperation(n)&&this.setState({error:String(e)})}}async startLoginFlow(e,t,n){if(this.isCurrentAuthOperation(n))try{let r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,t):await this.api.startInteractiveApiKeyLogin(e.id,t);if(!this.isCurrentAuthOperation(n)){if(r.status===`running`)try{await this.api.cancelOAuthFlow(r.flowId,t)}catch{}return}this.updateOAuthFlow(r,t),r.status===`running`&&this.startPolling(r.flowId,t)}catch(e){this.isCurrentAuthOperation(n)&&this.setState({error:String(e)})}}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&this.advanceAuthOperation();let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?Zs(n.flow):void 0,a=Zs(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.authOperationGeneration,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=Zs(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||Zs(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||Zs(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}advanceAuthOperation(){return this.authOperationGeneration+=1,this.stopPolling(),this.authOperationGeneration}isCurrentAuthOperation(e){return e===this.authOperationGeneration}currentOAuthDialog(e,t){if(!this.isCurrentAuthOperation(e))return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e=L(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(L(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function Xs(e,t){return e?.flowId===t.flowId&&e.requestId===t.requestId}function Zs(e){return e.prompt?.requestId??e.select?.requestId}function Qs(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 $s(e){return e.replaceAll(`:`,`.`)}function ec(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 tc(e,t){let n=ec(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function nc(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));rc(i,r)}function rc(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 ic(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:Cs(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:uc(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:uc(0,n),status:`uploading`,startedAt:e.startedAt}}function ac(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 oc(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=lc(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function sc(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,...lc(r),status:`error`,error:t,completedAt:n}}function cc(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,...lc(r),status:`cancelled`,error:n,completedAt:t}}function lc(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function uc(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var dc=class{constructor(e,t){this.getState=e,this.setState=t}report(e){this.reported=e,this.setState({error:e})}clear(){let e=this.reported;this.reported=void 0,!(e===void 0||this.getState().error!==e)&&this.setState({error:``})}},fc=$s(`core:workspace.files`),pc=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.fileRequestGeneration=0,this.reportedError=new dc(e,t),this.api=r.api??I,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Ts,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=L(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}),this.reportedError.clear()}catch(e){this.reportedError.report(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:gc(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,L(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries}}),this.reportedError.clear()}catch(e){this.reportedError.report(String(e))}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,selectedFileLoadError:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),nc(fc,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=++this.fileRequestGeneration,n=this.getState(),r=n.selectedProject,i=n.selectedWorkspace;if(r===void 0||i===void 0)return;let a={generation:t,machineId:L(n),projectId:r.id,workspaceId:i.id,path:e};this.setState({selectedFilePath:e,selectedFileContent:void 0,selectedFileLoadError:void 0});try{let e=await this.api.workspaceFile(a.projectId,a.workspaceId,a.path,a.machineId);if(!this.isCurrentFileRequest(a))return;this.setState({selectedFileContent:e,selectedFileLoadError:void 0}),this.reportedError.clear()}catch(e){if(!this.isCurrentFileRequest(a))return;this.setState({selectedFileContent:void 0,selectedFileLoadError:hc(e)})}}isCurrentFileRequest(e){let t=this.getState();return e.generation===this.fileRequestGeneration&&t.selectedFilePath===e.path&&t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&L(t)===e.machineId}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.reportedError.report(`Select a workspace before uploading files.`);return}if(e.length===0)return;let i=L(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=ic({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.reportedError.report(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(cc(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:gc(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(ac(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(oc(r,t,this.now())),this.reportedError.clear(),!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 bs)||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(mc(t)){let e=cc(n,this.now());return this.setUploadBatch(e),e}let r=hc(t),i=sc(n,r,this.now());return this.setUploadBatch(i),this.reportedError.report(r),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e}})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&L(t)===e.machineId}};function mc(e){return e instanceof ys}function hc(e){return e instanceof Error?e.message:String(e)}function gc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var _c=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 I.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineRuntimes:yc(this.getState().machineRuntimes,r),machineStatusSnapshots:yc(this.getState().machineStatusSnapshots,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:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Vs()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async updateMachine(e,t){this.setState({error:``});try{let n=await I.updateMachine(e.id,t);return this.setState({machines:this.getState().machines.map(e=>e.id===n.id?n:e)}),n}catch(e){this.setState({error:String(e)});return}}async addMachine(e){this.setState({error:``});try{let t=await I.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 I.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:vc(this.getState().machineStatuses,e.id),machineRuntimes:vc(this.getState().machineRuntimes,e.id),machineStatusSnapshots:vc(this.getState().machineStatusSnapshots,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 I.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 I.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 I.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=>I.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=>I.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 vc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function yc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var bc=class{constructor(e=0){if(this.debounceMs=e,this.pendingByKey=new Map,!Number.isInteger(e)||e<0)throw Error(`debounceMs must be a non-negative integer`)}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.phase===`running`?n.trailing=!0:this.rescheduleDebounce(n),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,phase:`debouncing`,trailing:!1,debounceTimer:void 0,finishDebounce:void 0};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1,r.phase=`debouncing`,this.debounceMs>0&&await this.waitForDebounce(r),r.phase=`running`;let n=r.latestRefresh;t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.cancelDebounce(r),this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}waitForDebounce(e){return new Promise(t=>{e.finishDebounce=t,this.rescheduleDebounce(e)})}rescheduleDebounce(e){e.finishDebounce!==void 0&&(e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=globalThis.setTimeout(()=>{let t=e.finishDebounce;e.debounceTimer=void 0,e.finishDebounce=void 0,e.phase=`running`,t?.()},this.debounceMs))}cancelDebounce(e){e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=void 0,e.finishDebounce=void 0}},xc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new bc,this.api=n.api??Oo}refresh(e){return this.refreshes.request(e,async()=>{this.apply(e,await this.api.machineStatus(e))})}apply(e,t){let n=this.getState().machineStatusSnapshots;Sc(n[e],t)&&this.setState({machineStatusSnapshots:{...n,[e]:t}})}};function Sc(e,t){return e===void 0||e.epochId!==t.epochId||t.revision>e.revision}var Cc=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??I}async loadProjects(){let e=L(this.getState());this.setState({error:``,isLoadingProjects:!0});try{let t=await this.api.projects(e);if(L(this.getState())!==e)return;let n=new Set(t.map(e=>e.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>n.has(e)));this.setState({projects:t,workspacesByProjectId:r})}catch(t){L(this.getState())===e&&this.setState({error:String(t)})}finally{L(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t,n){if(e.trim()===``)return;let r=L(this.getState());try{let i=await this.api.addProject(e.trim(),void 0,t,r);if(L(this.getState())!==r)return;let a=this.getState().projects;this.setState({projects:[...a.filter(e=>e.id!==i.id),i],projectDialogOpen:!1}),await this.workspaces.selectProject(i),n?.changed===!0&&await this.applyTrustChoice(i,n.trusted,r);return}catch(e){return wc(e)}}async applyTrustChoice(e,t,n){let r=this.getState().workspaces.find(e=>e.isMain);r!==void 0&&await this.api.setWorkspaceTrust(e.id,r.id,t,n)}async closeProject(e){let t=L(this.getState());try{if(await this.api.closeProject(e,t),L(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();this.setState({projects:n.projects.filter(t=>t.id!==e)}),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){L(this.getState())===t&&this.setState({error:String(e)})}}};function wc(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|no such file or directory/u.test(t)?`That folder does not exist. Tick “Create the folder if it does not exist” to make it, or correct the path.`:t.includes(`ENOTDIR`)?`That path is a file, not a folder.`:/EACCES|EPERM/u.test(t)?`That folder cannot be read with this account's permissions.`:t.replace(/^Error:\s*/u,``)}var Tc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??_o,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=L(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebStatus(e);this.isCurrent(e,t)&&this.setState({piWebStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=L(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({piWebStatus:t}),Ec(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 L(this.getState())===e&&t===this.requestSequence}};function Ec(e){if(e.release.error!==void 0)throw Error(`PI WEB update check failed: ${e.release.error}`);if(e.release.skipped===!0)throw Error(`PI WEB update check was skipped because remote version checks are disabled by offline/version-check settings`)}var Dc=`pi-web:cached-new-sessions:v1`,Oc=`browserCachedNew`,kc=`local`;function Ac(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function jc(e,t=kc,n=Ac()){if(e.messageCount!==0||e.archived===!0)return;let r=Lc(n).filter(n=>n.id!==e.id||n.machineId!==t);Rc([Mc(e,t),...r],n)}function Mc(e,t=kc){return{...e,browserCachedNew:!0,machineId:t}}function Nc(e,t=kc,n=Ac()){Rc(Lc(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Pc(e,t,n=kc,r=Ac()){let i=new Set(t.map(e=>e.id)),a=Lc(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&Rc(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Fc(e){return e!==void 0&&Bc(e)&&e.browserCachedNew===!0}function Ic(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:kc},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Lc(e=Ac()){try{let t=e?.getItem(Dc);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>zc(e)):[]}catch{return[]}}function Rc(e,t=Ac()){try{e.length===0?t?.removeItem(Dc):t?.setItem(Dc,JSON.stringify(e))}catch{}}function zc(e){if(!Vc(e))return[];let t=Hc(e,`id`),n=Hc(e,`path`),r=Hc(e,`cwd`),i=Hc(e,`created`),a=Hc(e,`modified`),o=Hc(e,`firstMessage`),s=Wc(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=Uc(e,`name`),l=Uc(e,`parentSessionPath`),u=Uc(e,`machineId`)??kc;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 Bc(e){return Oc in e}function Vc(e){return typeof e==`object`&&!!e}function Hc(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Uc(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function Wc(e,t){let n=e[t];return typeof n==`number`?n:void 0}function Gc(e){return hl(e.flatMap(Xc)).filter(e=>e.parts.length>0)}function Kc(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function qc(e,t){let n=il(t);return n===void 0?e:{...e,meta:n}}function Jc(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,Kc(t,n)]}function Yc(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 Xc(e){if(el(e))return[e];if(R(e,`role`)===`bashExecution`)return[qc(sl(e),e)];let t=R(e,`role`),n=cl(t),r=ll(Cl(e,`content`),e),i=t===`toolResult`?dl(R(e,`toolName`)??``,Cl(e,`details`)):void 0,a=i===void 0?r:[...r,i],o=n===`user`?tl(a):void 0;if(o!==void 0)return o.map(t=>qc(t,e));let s=rl(e);if(n===`tool`)return[qc({role:n,parts:a,...s===void 0?{}:{source:s}},e)];let c=a.filter(e=>e.type!==`empty`),l=n===`assistant`&&c.length>0&&c.every(e=>e.type===`skillRead`)?`skill`:n,u=c.length>0?[qc({role:l,parts:c,...s===void 0?{}:{source:s}},e)]:[],d=Zc(e);return d===void 0?u:[...u,qc(d,e)]}function Zc(e){if(R(e,`role`)!==`assistant`||R(e,`stopReason`)!==`error`)return;let t=R(e,`errorMessage`)?.trim();return Kc(`system`,`Model response failed: ${Qc(t===void 0||t===``?`The model returned an error.`:t,e)}`)}function Qc(e,t){if(!/aborted/iu.test(e))return e;let n=$c(t);return n===void 0?`${e} (the turn was stopped before it finished)`:`${e} (stopped while running ${n})`}function $c(e){let t=Cl(e,`content`);if(Array.isArray(t))for(let e=t.length-1;e>=0;--e){let n=t[e],r=R(n,`type`);if(r!==`toolCall`&&r!==`toolExecution`)continue;let i=R(n,`name`)??R(n,`toolName`);if(i!==void 0&&i!==``)return i}}function el(e){let t=R(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Cl(e,`parts`))}function tl(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=nl(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 nl(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 rl(e){let t=R(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function il(e){let t=al(Cl(e,`timestamp`)),n=ol(e),r=R(e,`thinkingLevel`);if(!(t===void 0&&n===void 0&&(r===void 0||r===``)))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n},...r===void 0||r===``?{}:{thinkingLevel:r}}}function al(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 ol(e){if(R(e,`role`)!==`assistant`)return;let t=R(e,`provider`),n=R(e,`model`),r=R(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 sl(e){let t=R(e,`command`)??``,n=wl(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Cl(e,`output`);r!=null&&n.push(``,El(r));let i=Cl(e,`exitCode`);i!=null&&n.push(``,`exit ${El(i)}`),wl(e,`cancelled`)===!0&&n.push(``,`cancelled`),wl(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=R(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
4
4
  `)}]}}function cl(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function ll(e,t){let n=ul(t);return n===void 0?typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=R(e,`type`),n=R(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=R(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=R(e,`name`)??`tool`,n=Cl(e,`arguments`),r=R(e,`id`),i=t===`read`?ml(R(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:bl(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=R(e,`data`),n=R(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return yl(e)}).map(e=>e.type===`text`&&R(t,`role`)===`toolResult`?pl(e.text,t):e):yl(e):[n]}function ul(e){if(!(R(e,`role`)!==`custom`||R(e,`customType`)!==`pi-web.ask.answers`))return fl(Cl(e,`details`))}function dl(e,t){if(e===`ask_user`)return fl(Cl(t,`superseded`))}function fl(e){try{return{type:`askUserRecord`,outcome:Bn(e)}}catch{return}}function pl(e,t){let n=R(t,`toolCallId`),r=Cl(t,`content`),i=Cl(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:R(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:wl(t,`isError`)===!0}}function ml(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 hl(e){let t=[],n=new Map;for(let r of e){let e=[],i={...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=gl(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&&_l(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function gl(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 _l(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=vl(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 vl(e){let t=Cl(e,`preview`);if(!Sl(t))return;let n=R(t,`diff`),r=R(t,`error`),i=Tl(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 yl(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:bl(e)}]:[{type:`text`,text:El(e)}]}function bl(e){if(!Sl(e))return El(e);let t=R(e,`command`);if(t!==void 0)return t;let n=R(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}: ${xl(t)}`).join(` · `)}function xl(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 Sl(e){return typeof e==`object`&&!!e}function Cl(e,t){return Sl(e)?e[t]:void 0}function R(e,t){let n=Cl(e,t);return typeof n==`string`?n:void 0}function wl(e,t){let n=Cl(e,t);return typeof n==`boolean`?n:void 0}function Tl(e,t){let n=Cl(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function El(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Dl=`pi-web:prompt-draft:`;function Ol(e){return`${Dl}${e}`}function kl(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Al(e,t=kl()){try{return t?.getItem(Ol(e))??``}catch{return``}}function jl(e,t,n=kl()){try{t?n?.setItem(Ol(e),t):n?.removeItem(Ol(e))}catch{}}function Ml(e,t=kl()){try{t?.removeItem(Ol(e))}catch{}}function Nl(e,t,n=kl()){let r=Al(e,n);r!==``&&(jl(t,r,n),Ml(e,n))}var Pl=`pi-web:ask-draft:`;function Fl(e,t){return`${Pl}${e}:${t}`}function Il(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Ll(e,t,n=Il()){try{let r=n?.getItem(Fl(e,t));return r==null?{}:Bl(r)}catch{return{}}}function Rl(e,t,n,r=Il()){try{let i=Object.entries(n).filter(([,e])=>e.values.length>0||(e.otherText??``)!==``);i.length===0?r?.removeItem(Fl(e,t)):r?.setItem(Fl(e,t),JSON.stringify(Object.fromEntries(i)))}catch{}}function zl(e,t,n=Il()){try{n?.removeItem(Fl(e,t))}catch{}}function Bl(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){let t=Vl(r);t!==void 0&&(n[e]=t)}return n}function Vl(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t={...e},n=t.values,r=t.otherText;if(!(!Array.isArray(n)||!n.every(e=>typeof e==`string`))&&!(r!==void 0&&typeof r!=`string`))return{values:[...n],...r===void 0?{}:{otherText:r}}}function Hl(e,t){return e.filter(e=>Gl(e,t[e.id])!==void 0).length}function Ul(e,t){return e.filter(e=>Gl(e,t[e.id])===void 0)}function Wl(e,t){let n=[];for(let r of e){let e=Gl(r,t[r.id]);e!==void 0&&n.push(e)}return{answers:n}}function Gl(e,t){if(t===void 0)return;let n=new Set(e.options.map(e=>e.value)),r=[...new Set(t.values)].filter(e=>n.has(e)),i=Kl(t.otherText);if(e.multiple!==!0&&r.length+(i===void 0?0:1)>1){let t=r[0];return t===void 0?i===void 0?void 0:{id:e.id,values:[],otherText:i}:{id:e.id,values:[t]}}if(!(r.length===0&&i===void 0))return{id:e.id,values:r,...i===void 0?{}:{otherText:i}}}function Kl(e){if(e===void 0)return;let t=e.trim().slice(0,Pt);return t===``?void 0:t}function ql(e,t){let n=Jl(t);if(n===void 0)return[...e,t];let r=e.length;for(;r>0;){let t=e[r-1],i=t===void 0?void 0:Jl(t);if(i===void 0||i<=n)break;--r}return r===e.length?[...e,t]:[...e.slice(0,r),t,...e.slice(r)]}function Jl(e){let t=e.meta?.timestamp;if(t===void 0||t===``)return;let n=Date.parse(t);return Number.isNaN(n)?void 0:n}function Yl(){let e=globalThis.crypto.randomUUID?.();return e===void 0?`cm-${String(Date.now())}-${Math.random().toString(36).slice(2,10)}`:e}function Xl(e,t,n=[]){let r=n.filter(e=>e.kind===`image`).map(e=>({type:`image`,mimeType:e.mimeType,data:e.data}));return{role:`user`,parts:e===``?[...r]:[{type:`text`,text:e},...r],meta:{delivery:{clientMessageId:t,state:`sending`}}}}function Zl(e,t){if(t.length===0)return[...e];let n=new Map;for(let t of e){let e=t.meta?.delivery;e?.state===`queued`&&n.set(e.clientMessageId,t)}let r=[];for(let e of t){let t=e.clientMessageId===void 0?void 0:n.get(e.clientMessageId);r.push(t??Ql(e))}let i=new Set(r);return[...e.filter(e=>!i.has(e)),...r]}function Ql(e){let t=e.clientMessageId??`queued:${e.kind}:${e.text}`;return{role:`user`,parts:[{type:`text`,text:e.text}],meta:{delivery:{clientMessageId:t,state:`queued`,kind:e.kind}}}}function $l(e,t){return e.findIndex(e=>e.meta?.delivery?.clientMessageId===t)}function eu(e,t,n,r){let i=$l(e,t);if(i===-1)return e;let a=e[i],o=a?.meta?.delivery;if(a===void 0||o===void 0||!ru(o.state,n)&&!tu(o.kind,r,o.state,n))return e;let s=[...e],c=ru(o.state,n)?n:o.state,l=r??o.kind;return s[i]={...a,meta:{...a.meta,delivery:{clientMessageId:t,state:c,...l===void 0?{}:{kind:l}}}},s}function tu(e,t,n,r){return t!==void 0&&t!==e&&n===`queued`&&r===`queued`}var nu={failed:-1,sending:0,received:1,queued:2,delivered:3};function ru(e,t){return e===t?!1:t===`failed`?e!==`delivered`:e!==`failed`&&nu[t]>nu[e]}function iu(e,t){let n=$l(e,t);if(n===-1)return[...e];let r=e[n];if(r?.meta?.delivery?.state!==`failed`)return[...e];let i=r.meta.delivery,a=[...e];return a[n]={...r,meta:{...r.meta,delivery:{clientMessageId:t,state:`sending`,...i.kind===void 0?{}:{kind:i.kind}}}},a}function au(e,t){let n=$l(e,t);return n===-1?[...e]:[...e.slice(0,n),...e.slice(n+1)]}function ou(e,t){let n=e,r=new Map;for(let e of t)e.clientMessageId!==void 0&&r.set(e.clientMessageId,e.kind);for(let t of e){let e=t.meta?.delivery;if(e===void 0)continue;let i=r.get(e.clientMessageId);if(i!==void 0){n=eu(n,e.clientMessageId,`queued`,i);continue}(e.state===`received`||e.state===`queued`)&&(n=eu(n,e.clientMessageId,`delivered`))}return n}function su(e,t){return t!==void 0&&$l(e,t)!==-1}function cu(e,t){let n=e.meta?.delivery;return n===void 0?t:{...t,meta:{...t.meta,delivery:{...n,state:n.state===`failed`?n.state:`delivered`}}}}function lu(e,t){return t===``?-1:e.findIndex(e=>e.role===`user`&&e.meta?.delivery!==void 0&&uu(e)===t)}function uu(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
@@ -468,6 +468,19 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
468
468
  button, [role="button"], input, select, summary { font: var(--pi-text-xs) var(--pi-font-ui); touch-action: manipulation; }
469
469
  :host { position: relative; z-index: 0; display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: var(--pi-text-base) var(--pi-font-ui); }
470
470
  .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
471
+ /* Sits over the transcript's bottom-right corner, clear of the reading
472
+ column, and only while the newest message is out of reach. 40px keeps it
473
+ above the 24px minimum target without becoming a second composer. */
474
+ .jump-to-bottom {
475
+ position: absolute; right: 12px; bottom: 12px; z-index: 4;
476
+ display: flex; align-items: center; justify-content: center;
477
+ width: 40px; height: 40px; padding: 0;
478
+ border: 1px solid var(--pi-border); border-radius: var(--pi-radius-pill);
479
+ background: var(--pi-surface); color: var(--pi-text);
480
+ font-size: 18px; line-height: 1; cursor: pointer;
481
+ box-shadow: 0 2px 8px rgb(0 0 0 / 25%);
482
+ }
483
+ .jump-to-bottom:hover, .jump-to-bottom:focus-visible { border-color: var(--pi-accent); }
471
484
  .top-notices { box-sizing: border-box; flex: 0 0 auto; max-height: 40%; min-height: 0; display: flex; flex-direction: column; overflow: hidden; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg-overlay); }
472
485
  /* Subagents strip: child sessions spawned by the parent conversation. The
473
486
  strip must read at one glance -- who is still working, who finished --
@@ -1184,7 +1197,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
1184
1197
  .viewer-header { align-items: flex-start; flex-direction: column; }
1185
1198
  .viewer-actions { width: 100%; flex-wrap: wrap; }
1186
1199
  }
1187
- `]}};H([b({attribute:!1})],wv.prototype,`machineId`,void 0),H([b({attribute:!1})],wv.prototype,`projectId`,void 0),H([b({attribute:!1})],wv.prototype,`workspaceId`,void 0),H([b({attribute:!1})],wv.prototype,`selectedPath`,void 0),H([b({attribute:!1})],wv.prototype,`file`,void 0),H([b({attribute:!1})],wv.prototype,`loadError`,void 0),H([b({attribute:!1})],wv.prototype,`previewUrlBuilder`,void 0),H([b({attribute:!1})],wv.prototype,`modeStore`,void 0),wv=H([y(`workspace-file-viewer`)],wv);function Tv(e){return JSON.stringify([e.machineId,e.projectId,e.workspaceId,e.selectedPath??null,e.file?.path??null,e.file?.modifiedAt??null,e.file?.mediaType??null])}function Ev(e){return e.mediaType===`image`?`image`:e.mediaType===`html`?`html`:e.mediaType===`pdf`?`pdf`:e.mediaType===`markdown`?`markdown`:e.binary?`download`:`code`}function Dv(e,t){return t!==`code`&&t!==`download`&&!e.binary}function Ov(e){return e===`html`?``:void 0}function kv(e){return e===`image`||e===`html`||e===`pdf`}function Av(e,t){return`${t===`code`?e.language??`text`:t===`download`?e.mimeType??`binary`:t===`markdown`?`markdown`:e.mimeType??t} · ${Nh(e.size)}${e.truncated?` · truncated`:``}`}function jv(){Cv(()=>import(`./CodeViewer-DWMYXHbj.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}var Mv=class extends v{constructor(...e){super(...e),this.destinationFolder=``,this.overwrite=!1,this.createDirs=!0,this.formError=``,this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,n=Rv(t?.files);t!==void 0&&(t.value=``),n.length>0&&this.openUploadReview(n)},this.handleDragEnter=e=>{zv(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{zv(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`copy`),this.dragActive=!0)},this.handleDragLeave=e=>{zv(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!zv(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;let t=Rv(e.dataTransfer?.files),n=this.context;t.length>0&&n!==void 0&&Iv(n,t)},this.handleDestinationInput=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??``,this.formError=``},this.handleCreateDirsChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has(`context`))return;let t=e.get(`context`);t!==void 0&&this.context!==void 0&&Lv(t)!==Lv(this.context)&&this.resetPendingUpload()}updated(){this.syncUploadModal()}disconnectedCallback(){this.releaseUploadModal(),super.disconnectedCallback()}render(){let e=this.context;return e===void 0?g`<p class="muted">Files unavailable.</p>`:g`
1200
+ `]}};H([b({attribute:!1})],wv.prototype,`machineId`,void 0),H([b({attribute:!1})],wv.prototype,`projectId`,void 0),H([b({attribute:!1})],wv.prototype,`workspaceId`,void 0),H([b({attribute:!1})],wv.prototype,`selectedPath`,void 0),H([b({attribute:!1})],wv.prototype,`file`,void 0),H([b({attribute:!1})],wv.prototype,`loadError`,void 0),H([b({attribute:!1})],wv.prototype,`previewUrlBuilder`,void 0),H([b({attribute:!1})],wv.prototype,`modeStore`,void 0),wv=H([y(`workspace-file-viewer`)],wv);function Tv(e){return JSON.stringify([e.machineId,e.projectId,e.workspaceId,e.selectedPath??null,e.file?.path??null,e.file?.modifiedAt??null,e.file?.mediaType??null])}function Ev(e){return e.mediaType===`image`?`image`:e.mediaType===`html`?`html`:e.mediaType===`pdf`?`pdf`:e.mediaType===`markdown`?`markdown`:e.binary?`download`:`code`}function Dv(e,t){return t!==`code`&&t!==`download`&&!e.binary}function Ov(e){return e===`html`?``:void 0}function kv(e){return e===`image`||e===`html`||e===`pdf`}function Av(e,t){return`${t===`code`?e.language??`text`:t===`download`?e.mimeType??`binary`:t===`markdown`?`markdown`:e.mimeType??t} · ${Nh(e.size)}${e.truncated?` · truncated`:``}`}function jv(){Cv(()=>import(`./CodeViewer-935R1s95.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}var Mv=class extends v{constructor(...e){super(...e),this.destinationFolder=``,this.overwrite=!1,this.createDirs=!0,this.formError=``,this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,n=Rv(t?.files);t!==void 0&&(t.value=``),n.length>0&&this.openUploadReview(n)},this.handleDragEnter=e=>{zv(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{zv(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`copy`),this.dragActive=!0)},this.handleDragLeave=e=>{zv(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!zv(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;let t=Rv(e.dataTransfer?.files),n=this.context;t.length>0&&n!==void 0&&Iv(n,t)},this.handleDestinationInput=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??``,this.formError=``},this.handleCreateDirsChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has(`context`))return;let t=e.get(`context`);t!==void 0&&this.context!==void 0&&Lv(t)!==Lv(this.context)&&this.resetPendingUpload()}updated(){this.syncUploadModal()}disconnectedCallback(){this.releaseUploadModal(),super.disconnectedCallback()}render(){let e=this.context;return e===void 0?g`<p class="muted">Files unavailable.</p>`:g`
1188
1201
  <section
1189
1202
  class=${this.dragActive?`files-panel dragging`:`files-panel`}
1190
1203
  @dragenter=${this.handleDragEnter}
@@ -1354,7 +1367,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
1354
1367
  .review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1355
1368
  .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; }
1356
1369
  footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
1357
- `]}};H([b({attribute:!1})],Mv.prototype,`context`,void 0),H([S(`#workspace-upload-input`)],Mv.prototype,`uploadInput`,void 0),H([S(`.dialog-backdrop`)],Mv.prototype,`uploadDialogBackdrop`,void 0),H([S(`.upload-dialog`)],Mv.prototype,`uploadDialog`,void 0),H([x()],Mv.prototype,`pendingUpload`,void 0),H([x()],Mv.prototype,`destinationFolder`,void 0),H([x()],Mv.prototype,`overwrite`,void 0),H([x()],Mv.prototype,`createDirs`,void 0),H([x()],Mv.prototype,`formError`,void 0),H([x()],Mv.prototype,`dragActive`,void 0),Mv=H([y(`workspace-files-panel`)],Mv);function Nv(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 Pv(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Cs(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Fv(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Iv(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Lv(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Rv(e){return e==null?[]:Array.from(e)}function zv(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Bv(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}function Vv(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function Hv(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 Uv(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return qv(e.percent)}}function Wv(e){return e.status===`uploading`?e.percent:1}function Gv(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return qv(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Kv(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Nh(e.loaded)} / ${Nh(e.total)}`:`Wrote ${e.response.path}`:e.error}function qv(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Jv(){return[{id:`workspace.files`,title:`Files`,icon:Ah(`files`),order:10,routeAliases:[`files`],render:Yv},{id:`workspace.terminal`,title:`Terminal`,icon:Ah(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Xv}]}function Yv(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Xv(e){return Zv(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Zv(){Cv(()=>import(`./TerminalPanel-FojQLt0o.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var Qv={apiVersion:2,name:`PI WEB Core`,activate:()=>({contributions:{actions:Sh(),workspacePanels:Jv()}})},$v={"--pi-bg":`#0d1117`,"--pi-surface":`#161b22`,"--pi-surface-hover":`#21262d`,"--pi-terminal-bg":`#05070a`,"--pi-terminal-text":`#e6edf3`,"--pi-border":`#30363d`,"--pi-border-muted":`#21262d`,"--pi-text":`#e6edf3`,"--pi-text-secondary":`#c9d1d9`,"--pi-text-bright":`#f0f6fc`,"--pi-muted":`#8b949e`,"--pi-dim":`#6e7681`,"--pi-accent":`#58a6ff`,"--pi-accent-border":`#2f81f7`,"--pi-selection-bg":`#0d2847`,"--pi-success":`#3fb950`,"--pi-success-border":`#238636`,"--pi-success-bg":`#0f1b12`,"--pi-success-surface":`#0f2a16`,"--pi-success-ring":`#3fb95055`,"--pi-warning":`#d29922`,"--pi-warning-border":`#6e5200`,"--pi-warning-surface":`#1f1a10`,"--pi-danger":`#ff7b72`,"--pi-purple":`#d2a8ff`,"--pi-purple-border":`#a371f7`,"--pi-purple-surface":`#21132f`,"--pi-overlay":`#0008`,"--pi-shadow-soft":`#0006`,"--pi-shadow":`#0008`,"--pi-shadow-strong":`#000b`,"--pi-bg-overlay-soft":`#0d1117dd`,"--pi-bg-overlay":`#0d1117e6`,"--pi-success-bg-overlay":`#0f1b12ee`,"--pi-terminal-selection":`#264f78`},ey={"--pi-bg":`#070912`,"--pi-surface":`#101527`,"--pi-surface-hover":`#151b31`,"--pi-terminal-bg":`#050710`,"--pi-terminal-text":`#f7f4ff`,"--pi-border":`#26304f`,"--pi-border-muted":`#26304f`,"--pi-text":`#f7f4ff`,"--pi-text-secondary":`#aaa4bd`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#aaa4bd`,"--pi-dim":`#817a99`,"--pi-accent":`#7c3cff`,"--pi-accent-border":`#5a47b0`,"--pi-selection-bg":`#1d2547`,"--pi-success":`#00f0d8`,"--pi-success-border":`#00f0d8`,"--pi-success-bg":`#071e22`,"--pi-success-surface":`#092d31`,"--pi-success-ring":`#00f0d855`,"--pi-warning":`#ffb000`,"--pi-warning-border":`#ffb000`,"--pi-warning-surface":`#16140d`,"--pi-danger":`#ff4f7b`,"--pi-purple":`#b7a2ff`,"--pi-purple-border":`#7c3cff`,"--pi-purple-surface":`#181026`,"--pi-overlay":`#0008`,"--pi-shadow-soft":`#0006`,"--pi-shadow":`#0008`,"--pi-shadow-strong":`#000b`,"--pi-bg-overlay-soft":`#070912dd`,"--pi-bg-overlay":`#070912e6`,"--pi-success-bg-overlay":`#071e22ee`,"--pi-terminal-selection":`#3d4a78`},ty={"--pi-bg":`#f7f1e6`,"--pi-surface":`#fff9ee`,"--pi-surface-hover":`#f0e6d6`,"--pi-terminal-bg":`#15131b`,"--pi-terminal-text":`#fff9ee`,"--pi-border":`#c9bca8`,"--pi-border-muted":`#d8cdbc`,"--pi-text":`#15131b`,"--pi-text-secondary":`#15131b`,"--pi-text-bright":`#15131b`,"--pi-muted":`#5f586a`,"--pi-dim":`#766f7e`,"--pi-accent":`#6430d8`,"--pi-accent-border":`#6430d8`,"--pi-selection-bg":`#eadff8`,"--pi-success":`#008c82`,"--pi-success-border":`#008c82`,"--pi-success-bg":`#e1f4ef`,"--pi-success-surface":`#d7f0ec`,"--pi-success-ring":`#008c8255`,"--pi-warning":`#b05f00`,"--pi-warning-border":`#b05f00`,"--pi-warning-surface":`#fff2d2`,"--pi-danger":`#b51d49`,"--pi-purple":`#6430d8`,"--pi-purple-border":`#6430d8`,"--pi-purple-surface":`#eadff8`,"--pi-overlay":`#15131b66`,"--pi-shadow-soft":`#15131b22`,"--pi-shadow":`#15131b33`,"--pi-shadow-strong":`#15131b44`,"--pi-bg-overlay-soft":`#f7f1e6dd`,"--pi-bg-overlay":`#f7f1e6e6`,"--pi-success-bg-overlay":`#e1f4efee`,"--pi-terminal-selection":`#8d7b64`},ny={"--pi-bg":`#000000`,"--pi-surface":`#0d0d0d`,"--pi-surface-hover":`#1a1a1a`,"--pi-terminal-bg":`#000000`,"--pi-terminal-text":`#ffffff`,"--pi-border":`#5c5c5c`,"--pi-border-muted":`#3d3d3d`,"--pi-text":`#ffffff`,"--pi-text-secondary":`#e6e6e6`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#b3b3b3`,"--pi-dim":`#8f8f8f`,"--pi-accent":`#4dc3ff`,"--pi-accent-border":`#4dc3ff`,"--pi-selection-bg":`#00263a`,"--pi-success":`#3ff05a`,"--pi-success-border":`#3ff05a`,"--pi-success-bg":`#001a06`,"--pi-success-surface":`#00280b`,"--pi-success-ring":`#3ff05a66`,"--pi-warning":`#ffcc33`,"--pi-warning-border":`#ffcc33`,"--pi-warning-surface":`#251c00`,"--pi-danger":`#ff6b6b`,"--pi-purple":`#c9a3ff`,"--pi-purple-border":`#c9a3ff`,"--pi-purple-surface":`#180d29`,"--pi-overlay":`#000000cc`,"--pi-shadow-soft":`#00000099`,"--pi-shadow":`#000000bb`,"--pi-shadow-strong":`#000000e6`,"--pi-bg-overlay-soft":`#000000dd`,"--pi-bg-overlay":`#000000f2`,"--pi-success-bg-overlay":`#001a06ee`,"--pi-terminal-selection":`#00456b`},ry={"--pi-bg":`#14110e`,"--pi-surface":`#1d1915`,"--pi-surface-hover":`#26211b`,"--pi-terminal-bg":`#100d0b`,"--pi-terminal-text":`#e8ddcc`,"--pi-border":`#3a3229`,"--pi-border-muted":`#2b2520`,"--pi-text":`#e8ddcc`,"--pi-text-secondary":`#cbbfad`,"--pi-text-bright":`#fff4e0`,"--pi-muted":`#9c9081`,"--pi-dim":`#7a6f62`,"--pi-accent":`#e0a35c`,"--pi-accent-border":`#b8813f`,"--pi-selection-bg":`#2e2415`,"--pi-success":`#8fbf6f`,"--pi-success-border":`#6d9954`,"--pi-success-bg":`#161c12`,"--pi-success-surface":`#1e2718`,"--pi-success-ring":`#8fbf6f55`,"--pi-warning":`#d9a441`,"--pi-warning-border":`#9c7429`,"--pi-warning-surface":`#241c0f`,"--pi-danger":`#d97b6c`,"--pi-purple":`#b79ad1`,"--pi-purple-border":`#8d74a8`,"--pi-purple-surface":`#221a2b`,"--pi-overlay":`#0a0806cc`,"--pi-shadow-soft":`#00000055`,"--pi-shadow":`#00000077`,"--pi-shadow-strong":`#000000aa`,"--pi-bg-overlay-soft":`#14110edd`,"--pi-bg-overlay":`#14110ee6`,"--pi-success-bg-overlay":`#161c12ee`,"--pi-terminal-selection":`#3d3121`},iy={"--pi-bg":`#fbfbf9`,"--pi-surface":`#ffffff`,"--pi-surface-hover":`#f1f1ee`,"--pi-terminal-bg":`#1c1c1a`,"--pi-terminal-text":`#fbfbf9`,"--pi-border":`#c7c7c1`,"--pi-border-muted":`#e0e0da`,"--pi-text":`#1c1c1a`,"--pi-text-secondary":`#33332f`,"--pi-text-bright":`#000000`,"--pi-muted":`#5e5e58`,"--pi-dim":`#7c7c75`,"--pi-accent":`#1f5fd0`,"--pi-accent-border":`#1f5fd0`,"--pi-selection-bg":`#e2ecfb`,"--pi-success":`#0f7a4a`,"--pi-success-border":`#0f7a4a`,"--pi-success-bg":`#e6f5ed`,"--pi-success-surface":`#d9efe3`,"--pi-success-ring":`#0f7a4a55`,"--pi-warning":`#8a5a00`,"--pi-warning-border":`#8a5a00`,"--pi-warning-surface":`#fdf0d5`,"--pi-danger":`#b02020`,"--pi-purple":`#5b3fc7`,"--pi-purple-border":`#5b3fc7`,"--pi-purple-surface":`#ece7fb`,"--pi-overlay":`#1c1c1a66`,"--pi-shadow-soft":`#1c1c1a1a`,"--pi-shadow":`#1c1c1a2b`,"--pi-shadow-strong":`#1c1c1a40`,"--pi-bg-overlay-soft":`#fbfbf9dd`,"--pi-bg-overlay":`#fbfbf9e6`,"--pi-success-bg-overlay":`#e6f5edee`,"--pi-terminal-selection":`#9ab4d8`},ay={apiVersion:2,name:`PI WEB Themes`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB Dark`,description:`Dark PI WEB palette.`,order:10,colorScheme:`dark`,tokens:ey},{id:`pi-web-light`,name:`PI WEB Light`,description:`Light PI WEB palette.`,order:20,colorScheme:`light`,tokens:ty},{id:`classic`,name:`PI WEB Classic`,description:`The original PI WEB dark palette.`,order:30,colorScheme:`dark`,tokens:$v},{id:`high-contrast`,name:`High Contrast`,description:`Near-black behind near-white, for bright rooms and tired eyes.`,order:40,colorScheme:`dark`,tokens:ny},{id:`night`,name:`Night`,description:`Warm and dim, with an amber accent instead of blue light.`,order:50,colorScheme:`dark`,tokens:ry},{id:`paper`,name:`Paper`,description:`Untinted ink on paper, for daylight and for screenshots.`,order:60,colorScheme:`light`,tokens:iy}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`Follow the system light/dark preference with PI WEB themes.`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})};async function oy(e=`pi-web-plugins/manifest.json`,t={}){let n=vt(e),r=await ly(n);if(r===void 0)return{registrations:[],failures:[]};let i=[],a=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=sy(e.module,n),a=my(await(t.moduleLoader??cy)(r),r);i.push({id:t.machineId===void 0?e.id:Gs(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...e.backendRevision===void 0?{}:{backendRevision:e.backendRevision},...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){a.push({entry:e,error:t})}return{registrations:i,failures:a}}function sy(e,t,n){return e.startsWith(`/`)?n===void 0?vt(e):vt(e,n):new URL(e,t).toString()}async function cy(e){return Cv(()=>import(e),[],import.meta.url)}async function ly(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(await dy(t));return uy(await t.json())}}function uy(e){if(!gy(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);let t=e.plugins.map(e=>{if(!gy(e)||typeof e.id!=`string`||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);let t=e.id;if(!en(t))throw Error(`Invalid plugin manifest id: ${t}`);if(tn(t))throw Error(`Reserved plugin manifest id: ${t}`);return{id:t,module:e.module,...fy(e.backendRevision),machineSpecific:py(e.machineSpecific)}}),n=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate plugin manifest id: ${e.id}`);n.add(e.id)}return{plugins:t}}async function dy(e){let t;try{let n=await e.json();if(gy(n)){let e=n.error,r=n.detail;t=typeof r==`string`?`${typeof e==`string`?`${e}: `:``}${r}`:typeof e==`string`?e:void 0}}catch{}return`Failed to load plugin manifest (${`${String(e.status)}${e.statusText===``?``:` ${e.statusText}`}`})${t===void 0?``:`: ${t}`}`}function fy(e){if(e===void 0)return{};try{return{backendRevision:$o(e)}}catch{throw Error(`Invalid plugin manifest entry`)}}function py(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function my(e,t){if(!gy(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(gy(n)&&n.apiVersion!==2)throw Error(`Unsupported browser plugin API version for ${t}: ${String(n.apiVersion)} (expected 2)`);if(!hy(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function hy(e){return gy(e)&&e.apiVersion===2&&typeof e.name==`string`&&typeof e.activate==`function`}function gy(e){return typeof e==`object`&&!!e}var _y=/^[a-z][a-z0-9.-]*$/u,vy=/^[a-z][a-z0-9.-]*$/u,yy=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,by=/^[a-z][a-z0-9.-]*(?::[a-z][a-z0-9.-]*)?$/u,xy=new WeakMap,Sy=new WeakMap,Cy=new WeakMap,wy=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.registeringPluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{plugin:t}=e,n=e.id,r=e.sourcePluginId??n;this.validatePluginId(n),this.validatePluginId(r);let i=this.parseMachineSpecific(n,e.machineSpecific),a=this.parseBackendRevision(n,e.backendRevision);if(this.pluginIds.has(n)||this.registeringPluginIds.has(n))throw Error(`Duplicate plugin id: ${n}`);if(!this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,i)){this.registeringPluginIds.add(n);try{let o=t.apiVersion;if(o!==2)throw Error(`Unsupported browser plugin API version for ${r}: ${String(o)} (expected 2)`);let s=t.activate(Object.freeze({apiVersion:2,pluginId:r,runtimePluginId:n,html:g,svg:Ye})).contributions,c=new Set,l=(s.actions??[]).map(t=>this.qualifyAction(n,t,e.machineId,e.sourcePluginId,c)),u=(s.workspacePanels??[]).map(t=>this.qualifyWorkspacePanel(n,t,e.machineId,e.sourcePluginId,a,c)),d=(s.workspaceLabels??[]).map(t=>this.qualifyWorkspaceLabelContribution(n,t,e.machineId,e.sourcePluginId,a,c)),f=e.machineId===void 0?(s.themes??[]).map(e=>this.qualifyTheme(n,e,c)):[],p=e.machineId===void 0?(s.themePairs??[]).map(e=>this.qualifyThemePair(n,e,c)):[];this.pluginIds.add(n);for(let e of c)this.contributionIds.add(e);this.actions.push(...l),this.workspacePanels.push(...u),this.workspaceLabels.push(...d),this.themes.push(...f),this.themePairs.push(...p),e.machineId===void 0?(this.gatewayPluginIds.add(n),i&&this.gatewayMachineSpecificPluginIds.add(n)):e.sourcePluginId!==void 0&&i&&My(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}finally{this.registeringPluginIds.delete(n)}}}hasPlugin(e){return this.pluginIds.has(e)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Fy(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Ty(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.shortcutAliases!==void 0&&(a.shortcutAliases=[...t.shortcutAliases]),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}resolveWorkspacePanelRouteId(e,t){let n=this.workspacePanels.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)),r=n.find(t=>t.id===e);if(r!==void 0)return r.id;let i=n.filter(t=>t.routeAliases?.includes(e)===!0);if(i.length===1)return i[0]?.id;i.length>1&&console.warn(`Ambiguous PI WEB workspace panel route: ${e}`)}async invalidateWorkspacePanels(e,t){await Promise.all(this.workspacePanels.map(async n=>{if(!(n.onInvalidate===void 0||t!==void 0&&n.id!==t))try{await n.onInvalidate(e)}catch(e){console.warn(`Failed to invalidate PI WEB plugin panel ${n.id}`,e)}}))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r,i){let a=this.qualify(e,t.id,i),o=`${r??e}:${t.id}`,s=this.parseShortcutAliases(a,t.shortcutAliases,o);return{...t,id:a,pluginId:e,localId:t.id,...s.length===0?{}:{shortcutAliases:s},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.badge,c=t.visible,l=t.onInvalidate,u=jy(e,r,i),d=`${r??e}:${t.id}`,f=this.parseRouteAliases(o,t.routeAliases,d);return{...t,id:o,pluginId:e,localId:t.id,...f.length===0?{}:{routeAliases:f},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(c?.(Ey(t,u))??!0),...s===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?s(Ey(t,u)):void 0},...l===void 0?{}:{onInvalidate:t=>this.isContributionActive(e,n,t.machine.id,r)?l(Ey(t,u)):void 0},render:e=>t.render(Ey(e,u))}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.visible,c=t.items,l=jy(e,r,i);return{...t,id:o,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(s?.(Dy(t,l))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?c(Dy(t,l)):[]}}qualifyTheme(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id}}qualifyThemePair(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t,n){this.validateLocalId(t);let r=`${e}:${t}`;if(this.contributionIds.has(r)||n.has(r))throw Error(`Duplicate contribution id: ${r}`);return n.add(r),r}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}parseShortcutAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!Ny(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(Ny)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!by.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}validatePluginId(e){if(!_y.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!vy.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return $o(t)}catch{throw Error(`Invalid plugin backend revision for ${e}`)}}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Py(t)}`);return t}};function Ty(e,t){return xy.get(e)?.(t)??e}function Ey(e,t){return Sy.get(e)?.(t)??e}function Dy(e,t){return Cy.get(e)?.(t)??e}function Oy(e,t){return xy.set(e,t),e}function ky(e,t){return Sy.set(e,t),e}function Ay(e,t){return Cy.set(e,t),e}function jy(e,t,n){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n}})}function My(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Ny(e){return yy.test(e)}function Py(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e==null)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Fy(e){return e.state.selectedMachine?.id??`local`}function Iy(e,t,n,r=cs){let i=e.backendRevision;if(i!==void 0)return{request:(a,o)=>r({pluginId:e.sourcePluginId,backendRevision:i,machineId:n,projectId:t.projectId,workspaceId:t.id},a,o)}}function Ly(e,t,n,r){return{readFile:r=>e.workspaceFile(t.projectId,t.id,r,n),listFiles:r=>e.workspaceTree(t.projectId,t.id,r,n),writeFile:async(i,a,o)=>{let s=await e.writeWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s},deleteFile:async i=>{let a=await e.deleteWorkspaceFile(t.projectId,t.id,i,n);return r?.(),a},moveFile:async(i,a,o)=>{let s=await e.moveWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s}}}var Ry=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function zy(){return typeof window>`u`||!(`matchMedia`in window)?[]:Ry.map(e=>window.matchMedia(e))}function By(e,t=Vy()){return e.some(e=>e.matches)||Hy(t)}function Vy(){return typeof navigator>`u`?void 0:navigator}function Hy(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Uy=class{constructor(e=Wy()){this.scheduler=e}repair(e){if(!e){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},250)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);let e=this.scheduler.documentElement;e!==void 0&&(e.scrollTop=0);let t=this.scheduler.body;t!==void 0&&(t.scrollTop=0)}};function Wy(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>`u`?void 0:document.documentElement},get body(){return typeof document>`u`?void 0:document.body}}}var Gy=`(max-width: 760px)`,Ky=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=By(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??qy(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??zy(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Uy,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=By(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(e={}){return Jy(this.isMobileNavigationLayout,e)}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function qy(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(Gy)}function Jy(e,t){return e&&(t.sessionId??``)===``?`navigation`:`chat`}var Yy=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new bc,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Xy(),this.documentTarget=t.documentTarget??Zy(),this.isDocumentVisible=t.isDocumentVisible??Qy,this.scheduleFrame=t.scheduleFrame??$y}connect(){this.connected||(this.connected=!0,this.windowTarget?.addEventListener(`focus`,this.onFocus),this.documentTarget?.addEventListener(`visibilitychange`,this.onVisibilityChange))}disconnect(){this.connected&&(this.connected=!1,this.windowTarget?.removeEventListener(`focus`,this.onFocus),this.documentTarget?.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.scheduledRefresh?.cancel(),this.scheduledRefresh=void 0)}handleResumeSignal(){this.callbacks.onResumeSignal(),this.scheduledRefresh===void 0&&(this.scheduledRefresh=this.scheduleFrame(()=>{this.scheduledRefresh=void 0,this.connected&&this.refreshes.request(`browser-resume`,async()=>{this.connected&&await this.callbacks.refreshAfterResume()}).catch(e=>{this.callbacks.onRefreshError(e)})}))}};function Xy(){return typeof window>`u`?void 0:window}function Zy(){return typeof document>`u`?void 0:document}function Qy(){return typeof document>`u`||document.visibilityState===`visible`}function $y(e){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){let t=window.requestAnimationFrame(()=>{e()});return{cancel:()=>{window.cancelAnimationFrame(t)}}}let t=globalThis.setTimeout(e,0);return{cancel:()=>{globalThis.clearTimeout(t)}}}var eb=[`machines`,`projects`,`workspaces`,`sessions`];function tb(e){return e.selectedWorkspace===void 0?e.selectedProject===void 0?`projects`:`workspaces`:`sessions`}function nb(e,t){if(e!==`none`)return e??tb(t)}function rb(e,t){return nb(t.expanded,t.state)!==e}function ib(e,t,n){return nb(e,n.state)===t?`none`:t}function ab(e){return e.workspaceCount===1?`sessions`:`workspaces`}function ob(e){return eb[eb.indexOf(e)+1]}var sb=class{hostConnected(){}constructor(e,t){this.host=e,this.getState=t,e.addController(this)}expandedSection(){return nb(this.expanded,this.getState())}isCollapsed(e){return rb(e,{expanded:this.expanded,state:this.getState()})}toggle(e){this.setExpanded(ib(this.expanded,e,{state:this.getState()}))}expand(e){this.setExpanded(e)}advanceAfterSelection(e,t){let n=e===`projects`?ab({workspaceCount:t?.workspaceCount}):ob(e);n!==void 0&&this.expand(n)}open(e,t){this.expand(e),t()}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}},cb=class{hostConnected(){}constructor(e){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this)}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(e,t=!0){return[`shell`,ub(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...lb(this.workspacePanelCollapsed,t)?[]:[`workspace-panel-collapsed`]].join(` `)}};function lb(e,t){return!e&&t}function ub(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var db=`pi-web:panel-sizes:v1`,fb={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},pb=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??Db(),this.panelSizes=yb(this.storage)}hostConnected(){}constraints(e){return mb(e)}panelWidth(e,t){return vb(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=vb(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Cb(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=wb(this.panelSizes,e),t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(e={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},e.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){bb(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${Eb(vb(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${Eb(vb(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function mb(e){return fb[e]}function hb(e,t,n){return e===`navigation`?n-t:t-n}function gb(e,t,n,r,i=mb(e)){return vb(e,t+hb(e,n,r),i)}function _b(e,t,n,r={}){let i=r.constraints??mb(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=Tb(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return vb(e,t+a,i)}function vb(e,t,n=mb(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function yb(e=Db()){try{let t=e?.getItem(db);return t==null||t===``?{}:xb(JSON.parse(t))}catch{return{}}}function bb(e,t=Db()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(db);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=vb(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=vb(`workspace`,e.workspacePanelWidth)),t.setItem(db,JSON.stringify(n))}catch{}}function xb(e){if(!Ob(e)||e.version!==1)return{};let t={},n=Sb(e.navigationPanelWidth),r=Sb(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=vb(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=vb(`workspace`,r)),t}function Sb(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Cb(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function wb(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Tb(e,t,n){if(e===`navigation`)return t===`ArrowRight`?n:t===`ArrowLeft`?-n:void 0;if(t===`ArrowLeft`)return n;if(t===`ArrowRight`)return-n}function Eb(e){return`${String(Math.round(e))}px`}function Db(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function Ob(e){return typeof e==`object`&&!!e}function kb(){let e=new URLSearchParams(window.location.search);return{machineId:Nb(e.get(`machine`)),projectId:Nb(e.get(`project`)),workspaceId:Nb(e.get(`workspace`)),sessionId:Nb(e.get(`session`)),tool:Nb(e.get(`tool`)),view:Nb(e.get(`view`))}}function Ab(e,t){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool===void 0?void 0:jb(e.tool,t),view:e.view===`chat`?`chat`:e.view===void 0?void 0:jb(e.view,t)}}function jb(e,t){return t(e)??(Pb(e)?e:void 0)}function Mb(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&e.tool!==``&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&e.view!==``&&n.searchParams.set(`view`,e.view),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function Nb(e){return e===null||e===``?void 0:e}function Pb(e){return/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Fb(){return Lb(new URLSearchParams(window.location.search).get(`settings`))}function Ib(e,t){let n=new URL(window.location.href);e===void 0?n.searchParams.delete(`settings`):n.searchParams.set(`settings`,e),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function Lb(e){if(e===`general`)return`general`;if(e===`appearance`||e===`theme`||e===`themes`)return`appearance`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`machines`)return`machines`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function Rb(e,t){return t===void 0?e:e.map(e=>Bb(e,t))}function zb(e,t){let n=new Set(Wp(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return Rb(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?Vb(e):e)}function Bb(e,t){let n=Zp(e,t);return n===void 0?e:n===null?Vb(e):{...e,shortcut:n}}function Vb(e){let t={...e};return delete t.shortcut,t}function Hb(e,t){let n=t.api??No,r=t.pollIntervalMs??1e3,i=t.setTimeout??Gb(),a=t.clearTimeout??Kb();return{async runCommand(o){let s=await n.runTerminalCommand(e,o);return o.open===!0&&t.openTerminal(o.workspace,{terminalId:s.terminalId}),{run:s,completed:Ub(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Ub(e,t,n,r,i){return Wb(e)?Promise.resolve(e):new Promise((a,o)=>{let s,c=!1,l=e=>{c||(c=!0,s!==void 0&&i(s),a(e))},u=e=>{c||(c=!0,s!==void 0&&i(s),o(e instanceof Error?e:Error(String(e))))},d=()=>{t.getCommandRun(e.id).then(e=>{if(e!==void 0&&Wb(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function Wb(e){return e.status===`succeeded`||e.status===`failed`}function Gb(){return(e,t)=>globalThis.setTimeout(e,t)}function Kb(){return e=>{globalThis.clearTimeout(e)}}var qb=class{constructor(e){this.callbacks=e,this.fired=!1}start(e){this.cancel(),this.origin=e,this.fired=!1,this.handle=this.callbacks.setTimer(()=>{this.handle=void 0,this.fired=!0,this.callbacks.onLongPress()},500)}move(e){if(this.origin===void 0)return;let t=Math.abs(e.clientX-this.origin.clientX),n=Math.abs(e.clientY-this.origin.clientY);(t>10||n>10)&&this.cancel()}cancel(){this.handle!==void 0&&this.callbacks.clearTimer(this.handle),this.handle=void 0,this.origin=void 0}consumeSuppressedClick(){let e=this.fired;return this.fired=!1,e}},Jb=class{constructor(e){this.open=e,this.longPress=new qb({onLongPress:()=>{this.heldId!==void 0&&this.open(this.heldId,this.heldAnchor??null)},setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>{window.clearTimeout(e)}})}pointerDown(e,t){t.pointerType!==`mouse`&&(this.heldId=e,this.heldAnchor=t.currentTarget,this.longPress.start(t))}pointerMove(e){this.longPress.move(e)}cancel(){this.longPress.cancel(),this.heldId=void 0,this.heldAnchor=void 0}consumeSuppressedClick(){return this.longPress.consumeSuppressedClick()}contextMenu(e,t){t.preventDefault(),this.open(e,t.currentTarget)}},Yb=0,Xb=120;function Zb(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?$b():Qb(e),i=window.innerWidth,a=window.innerHeight,o=Math.max(0,r.left),s=Math.min(i,r.right),c=Math.max(0,r.top),l=Math.min(a,r.bottom),u=Math.min(n.right,s),d=l-n.bottom-Yb,f=n.top-c-Yb;return[...d<Xb&&f>d?[`bottom: ${ex(a-n.top+Yb)};`,`max-height: ${ex(Math.max(0,f))};`]:[`top: ${ex(n.bottom+Yb)};`,`max-height: ${ex(Math.max(0,d))};`],`right: ${ex(Math.max(0,i-u))};`,`max-width: ${ex(Math.max(0,u-o))};`].join(` `)}function Qb(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():$b()}function $b(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function ex(e){return`${String(Math.round(e))}px`}function tx(e,t=`Active`,n){if(e===void 0)return n===void 0?void 0:g`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function nx(e){if(e!==void 0)return e[zt.working]===!0?`session`:e[zt.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==zt.unread)?`session`:void 0}function rx(e){return e?.[zt.unread]===!0}var ix={working:`Session is working`,idle:`Session is done`,asking:`Waiting for your answer`,error:`Session hit an error`};function ax(e,t){if(e===void 0)return t===void 0?void 0:g`<span class="session-state unread" role="img" aria-label=${t} title=${t}></span>`;let n=e===`sending`?`Sending message`:ix[e],r=t===void 0?n:`${t} · ${n}`;if(e===`idle`)return g`<span class=${t===void 0?`session-state idle`:`session-state idle unread`} role="img" aria-label=${r} title=${r}></span>`;if(e===`working`||e===`sending`){let i=e===`working`?[0,1,2].map(e=>g`<span class="state-dot working-dot" style=${`animation-delay:${(e*.14).toFixed(2)}s`}></span>`):null;return t===void 0?g`<span class="session-state working" role="img" aria-label=${n} title=${n}><span class="state-dots">${i}</span></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class="session-state working" aria-hidden="true"><span class="state-dots">${i}</span></span></span>`}return t===void 0?g`<span class=${`session-state ${e}`} role="img" aria-label=${n} title=${n}></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`session-state ${e}`} aria-hidden="true"></span></span>`}function ox(e,t=`Active`,n){let r=tx(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var sx=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function cx(e){return e.composedPath().some(e=>lx(e,sx))}function lx(e,t){if(typeof Element<`u`&&e instanceof Element)return e.matches(t);if(!(`matches`in e))return!1;let{matches:n}=e;return typeof n==`function`&&n.call(e,t)===!0}function ux(e,t){return cx(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?fx(e,()=>{px(e.currentTarget,-1)}):e.key===`ArrowDown`?fx(e,()=>{px(e.currentTarget,1)}):e.key===`Home`?fx(e,()=>{mx(e.currentTarget,0)}):e.key===`End`?fx(e,()=>{mx(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?fx(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?fx(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&fx(e,t.cancel)}function dx(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n==null?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function fx(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function px(e,t){let n=gx(e),r=vx(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||hx(n,i+t)}function mx(e,t){let n=gx(e);n.length!==0&&hx(n,t<0?n.length-1:t)}function hx(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function gx(e){let t=vx(e)?.getRootNode();return t===void 0||!_x(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function _x(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function vx(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var U=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.gestures=new Jb((e,t)=>{this.openMenu(e,t)}),this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.openMenuMachineId!==void 0&&!this.machines.some(e=>e.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,dx(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
1370
+ `]}};H([b({attribute:!1})],Mv.prototype,`context`,void 0),H([S(`#workspace-upload-input`)],Mv.prototype,`uploadInput`,void 0),H([S(`.dialog-backdrop`)],Mv.prototype,`uploadDialogBackdrop`,void 0),H([S(`.upload-dialog`)],Mv.prototype,`uploadDialog`,void 0),H([x()],Mv.prototype,`pendingUpload`,void 0),H([x()],Mv.prototype,`destinationFolder`,void 0),H([x()],Mv.prototype,`overwrite`,void 0),H([x()],Mv.prototype,`createDirs`,void 0),H([x()],Mv.prototype,`formError`,void 0),H([x()],Mv.prototype,`dragActive`,void 0),Mv=H([y(`workspace-files-panel`)],Mv);function Nv(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 Pv(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Cs(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Fv(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Iv(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Lv(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Rv(e){return e==null?[]:Array.from(e)}function zv(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Bv(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}function Vv(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function Hv(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 Uv(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return qv(e.percent)}}function Wv(e){return e.status===`uploading`?e.percent:1}function Gv(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return qv(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Kv(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Nh(e.loaded)} / ${Nh(e.total)}`:`Wrote ${e.response.path}`:e.error}function qv(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Jv(){return[{id:`workspace.files`,title:`Files`,icon:Ah(`files`),order:10,routeAliases:[`files`],render:Yv},{id:`workspace.terminal`,title:`Terminal`,icon:Ah(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Xv}]}function Yv(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Xv(e){return Zv(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Zv(){Cv(()=>import(`./TerminalPanel-BY9VIA1-.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var Qv={apiVersion:2,name:`PI WEB Core`,activate:()=>({contributions:{actions:Sh(),workspacePanels:Jv()}})},$v={"--pi-bg":`#0d1117`,"--pi-surface":`#161b22`,"--pi-surface-hover":`#21262d`,"--pi-terminal-bg":`#05070a`,"--pi-terminal-text":`#e6edf3`,"--pi-border":`#30363d`,"--pi-border-muted":`#21262d`,"--pi-text":`#e6edf3`,"--pi-text-secondary":`#c9d1d9`,"--pi-text-bright":`#f0f6fc`,"--pi-muted":`#8b949e`,"--pi-dim":`#6e7681`,"--pi-accent":`#58a6ff`,"--pi-accent-border":`#2f81f7`,"--pi-selection-bg":`#0d2847`,"--pi-success":`#3fb950`,"--pi-success-border":`#238636`,"--pi-success-bg":`#0f1b12`,"--pi-success-surface":`#0f2a16`,"--pi-success-ring":`#3fb95055`,"--pi-warning":`#d29922`,"--pi-warning-border":`#6e5200`,"--pi-warning-surface":`#1f1a10`,"--pi-danger":`#ff7b72`,"--pi-purple":`#d2a8ff`,"--pi-purple-border":`#a371f7`,"--pi-purple-surface":`#21132f`,"--pi-overlay":`#0008`,"--pi-shadow-soft":`#0006`,"--pi-shadow":`#0008`,"--pi-shadow-strong":`#000b`,"--pi-bg-overlay-soft":`#0d1117dd`,"--pi-bg-overlay":`#0d1117e6`,"--pi-success-bg-overlay":`#0f1b12ee`,"--pi-terminal-selection":`#264f78`},ey={"--pi-bg":`#070912`,"--pi-surface":`#101527`,"--pi-surface-hover":`#151b31`,"--pi-terminal-bg":`#050710`,"--pi-terminal-text":`#f7f4ff`,"--pi-border":`#26304f`,"--pi-border-muted":`#26304f`,"--pi-text":`#f7f4ff`,"--pi-text-secondary":`#aaa4bd`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#aaa4bd`,"--pi-dim":`#817a99`,"--pi-accent":`#7c3cff`,"--pi-accent-border":`#5a47b0`,"--pi-selection-bg":`#1d2547`,"--pi-success":`#00f0d8`,"--pi-success-border":`#00f0d8`,"--pi-success-bg":`#071e22`,"--pi-success-surface":`#092d31`,"--pi-success-ring":`#00f0d855`,"--pi-warning":`#ffb000`,"--pi-warning-border":`#ffb000`,"--pi-warning-surface":`#16140d`,"--pi-danger":`#ff4f7b`,"--pi-purple":`#b7a2ff`,"--pi-purple-border":`#7c3cff`,"--pi-purple-surface":`#181026`,"--pi-overlay":`#0008`,"--pi-shadow-soft":`#0006`,"--pi-shadow":`#0008`,"--pi-shadow-strong":`#000b`,"--pi-bg-overlay-soft":`#070912dd`,"--pi-bg-overlay":`#070912e6`,"--pi-success-bg-overlay":`#071e22ee`,"--pi-terminal-selection":`#3d4a78`},ty={"--pi-bg":`#f7f1e6`,"--pi-surface":`#fff9ee`,"--pi-surface-hover":`#f0e6d6`,"--pi-terminal-bg":`#15131b`,"--pi-terminal-text":`#fff9ee`,"--pi-border":`#c9bca8`,"--pi-border-muted":`#d8cdbc`,"--pi-text":`#15131b`,"--pi-text-secondary":`#15131b`,"--pi-text-bright":`#15131b`,"--pi-muted":`#5f586a`,"--pi-dim":`#766f7e`,"--pi-accent":`#6430d8`,"--pi-accent-border":`#6430d8`,"--pi-selection-bg":`#eadff8`,"--pi-success":`#008c82`,"--pi-success-border":`#008c82`,"--pi-success-bg":`#e1f4ef`,"--pi-success-surface":`#d7f0ec`,"--pi-success-ring":`#008c8255`,"--pi-warning":`#b05f00`,"--pi-warning-border":`#b05f00`,"--pi-warning-surface":`#fff2d2`,"--pi-danger":`#b51d49`,"--pi-purple":`#6430d8`,"--pi-purple-border":`#6430d8`,"--pi-purple-surface":`#eadff8`,"--pi-overlay":`#15131b66`,"--pi-shadow-soft":`#15131b22`,"--pi-shadow":`#15131b33`,"--pi-shadow-strong":`#15131b44`,"--pi-bg-overlay-soft":`#f7f1e6dd`,"--pi-bg-overlay":`#f7f1e6e6`,"--pi-success-bg-overlay":`#e1f4efee`,"--pi-terminal-selection":`#8d7b64`},ny={"--pi-bg":`#000000`,"--pi-surface":`#0d0d0d`,"--pi-surface-hover":`#1a1a1a`,"--pi-terminal-bg":`#000000`,"--pi-terminal-text":`#ffffff`,"--pi-border":`#5c5c5c`,"--pi-border-muted":`#3d3d3d`,"--pi-text":`#ffffff`,"--pi-text-secondary":`#e6e6e6`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#b3b3b3`,"--pi-dim":`#8f8f8f`,"--pi-accent":`#4dc3ff`,"--pi-accent-border":`#4dc3ff`,"--pi-selection-bg":`#00263a`,"--pi-success":`#3ff05a`,"--pi-success-border":`#3ff05a`,"--pi-success-bg":`#001a06`,"--pi-success-surface":`#00280b`,"--pi-success-ring":`#3ff05a66`,"--pi-warning":`#ffcc33`,"--pi-warning-border":`#ffcc33`,"--pi-warning-surface":`#251c00`,"--pi-danger":`#ff6b6b`,"--pi-purple":`#c9a3ff`,"--pi-purple-border":`#c9a3ff`,"--pi-purple-surface":`#180d29`,"--pi-overlay":`#000000cc`,"--pi-shadow-soft":`#00000099`,"--pi-shadow":`#000000bb`,"--pi-shadow-strong":`#000000e6`,"--pi-bg-overlay-soft":`#000000dd`,"--pi-bg-overlay":`#000000f2`,"--pi-success-bg-overlay":`#001a06ee`,"--pi-terminal-selection":`#00456b`},ry={"--pi-bg":`#14110e`,"--pi-surface":`#1d1915`,"--pi-surface-hover":`#26211b`,"--pi-terminal-bg":`#100d0b`,"--pi-terminal-text":`#e8ddcc`,"--pi-border":`#3a3229`,"--pi-border-muted":`#2b2520`,"--pi-text":`#e8ddcc`,"--pi-text-secondary":`#cbbfad`,"--pi-text-bright":`#fff4e0`,"--pi-muted":`#9c9081`,"--pi-dim":`#7a6f62`,"--pi-accent":`#e0a35c`,"--pi-accent-border":`#b8813f`,"--pi-selection-bg":`#2e2415`,"--pi-success":`#8fbf6f`,"--pi-success-border":`#6d9954`,"--pi-success-bg":`#161c12`,"--pi-success-surface":`#1e2718`,"--pi-success-ring":`#8fbf6f55`,"--pi-warning":`#d9a441`,"--pi-warning-border":`#9c7429`,"--pi-warning-surface":`#241c0f`,"--pi-danger":`#d97b6c`,"--pi-purple":`#b79ad1`,"--pi-purple-border":`#8d74a8`,"--pi-purple-surface":`#221a2b`,"--pi-overlay":`#0a0806cc`,"--pi-shadow-soft":`#00000055`,"--pi-shadow":`#00000077`,"--pi-shadow-strong":`#000000aa`,"--pi-bg-overlay-soft":`#14110edd`,"--pi-bg-overlay":`#14110ee6`,"--pi-success-bg-overlay":`#161c12ee`,"--pi-terminal-selection":`#3d3121`},iy={"--pi-bg":`#fbfbf9`,"--pi-surface":`#ffffff`,"--pi-surface-hover":`#f1f1ee`,"--pi-terminal-bg":`#1c1c1a`,"--pi-terminal-text":`#fbfbf9`,"--pi-border":`#c7c7c1`,"--pi-border-muted":`#e0e0da`,"--pi-text":`#1c1c1a`,"--pi-text-secondary":`#33332f`,"--pi-text-bright":`#000000`,"--pi-muted":`#5e5e58`,"--pi-dim":`#7c7c75`,"--pi-accent":`#1f5fd0`,"--pi-accent-border":`#1f5fd0`,"--pi-selection-bg":`#e2ecfb`,"--pi-success":`#0f7a4a`,"--pi-success-border":`#0f7a4a`,"--pi-success-bg":`#e6f5ed`,"--pi-success-surface":`#d9efe3`,"--pi-success-ring":`#0f7a4a55`,"--pi-warning":`#8a5a00`,"--pi-warning-border":`#8a5a00`,"--pi-warning-surface":`#fdf0d5`,"--pi-danger":`#b02020`,"--pi-purple":`#5b3fc7`,"--pi-purple-border":`#5b3fc7`,"--pi-purple-surface":`#ece7fb`,"--pi-overlay":`#1c1c1a66`,"--pi-shadow-soft":`#1c1c1a1a`,"--pi-shadow":`#1c1c1a2b`,"--pi-shadow-strong":`#1c1c1a40`,"--pi-bg-overlay-soft":`#fbfbf9dd`,"--pi-bg-overlay":`#fbfbf9e6`,"--pi-success-bg-overlay":`#e6f5edee`,"--pi-terminal-selection":`#9ab4d8`},ay={apiVersion:2,name:`PI WEB Themes`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB Dark`,description:`Dark PI WEB palette.`,order:10,colorScheme:`dark`,tokens:ey},{id:`pi-web-light`,name:`PI WEB Light`,description:`Light PI WEB palette.`,order:20,colorScheme:`light`,tokens:ty},{id:`classic`,name:`PI WEB Classic`,description:`The original PI WEB dark palette.`,order:30,colorScheme:`dark`,tokens:$v},{id:`high-contrast`,name:`High Contrast`,description:`Near-black behind near-white, for bright rooms and tired eyes.`,order:40,colorScheme:`dark`,tokens:ny},{id:`night`,name:`Night`,description:`Warm and dim, with an amber accent instead of blue light.`,order:50,colorScheme:`dark`,tokens:ry},{id:`paper`,name:`Paper`,description:`Untinted ink on paper, for daylight and for screenshots.`,order:60,colorScheme:`light`,tokens:iy}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`Follow the system light/dark preference with PI WEB themes.`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})};async function oy(e=`pi-web-plugins/manifest.json`,t={}){let n=vt(e),r=await ly(n);if(r===void 0)return{registrations:[],failures:[]};let i=[],a=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=sy(e.module,n),a=my(await(t.moduleLoader??cy)(r),r);i.push({id:t.machineId===void 0?e.id:Gs(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...e.backendRevision===void 0?{}:{backendRevision:e.backendRevision},...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){a.push({entry:e,error:t})}return{registrations:i,failures:a}}function sy(e,t,n){return e.startsWith(`/`)?n===void 0?vt(e):vt(e,n):new URL(e,t).toString()}async function cy(e){return Cv(()=>import(e),[],import.meta.url)}async function ly(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(await dy(t));return uy(await t.json())}}function uy(e){if(!gy(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);let t=e.plugins.map(e=>{if(!gy(e)||typeof e.id!=`string`||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);let t=e.id;if(!en(t))throw Error(`Invalid plugin manifest id: ${t}`);if(tn(t))throw Error(`Reserved plugin manifest id: ${t}`);return{id:t,module:e.module,...fy(e.backendRevision),machineSpecific:py(e.machineSpecific)}}),n=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate plugin manifest id: ${e.id}`);n.add(e.id)}return{plugins:t}}async function dy(e){let t;try{let n=await e.json();if(gy(n)){let e=n.error,r=n.detail;t=typeof r==`string`?`${typeof e==`string`?`${e}: `:``}${r}`:typeof e==`string`?e:void 0}}catch{}return`Failed to load plugin manifest (${`${String(e.status)}${e.statusText===``?``:` ${e.statusText}`}`})${t===void 0?``:`: ${t}`}`}function fy(e){if(e===void 0)return{};try{return{backendRevision:$o(e)}}catch{throw Error(`Invalid plugin manifest entry`)}}function py(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function my(e,t){if(!gy(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(gy(n)&&n.apiVersion!==2)throw Error(`Unsupported browser plugin API version for ${t}: ${String(n.apiVersion)} (expected 2)`);if(!hy(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function hy(e){return gy(e)&&e.apiVersion===2&&typeof e.name==`string`&&typeof e.activate==`function`}function gy(e){return typeof e==`object`&&!!e}var _y=/^[a-z][a-z0-9.-]*$/u,vy=/^[a-z][a-z0-9.-]*$/u,yy=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,by=/^[a-z][a-z0-9.-]*(?::[a-z][a-z0-9.-]*)?$/u,xy=new WeakMap,Sy=new WeakMap,Cy=new WeakMap,wy=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.registeringPluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{plugin:t}=e,n=e.id,r=e.sourcePluginId??n;this.validatePluginId(n),this.validatePluginId(r);let i=this.parseMachineSpecific(n,e.machineSpecific),a=this.parseBackendRevision(n,e.backendRevision);if(this.pluginIds.has(n)||this.registeringPluginIds.has(n))throw Error(`Duplicate plugin id: ${n}`);if(!this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,i)){this.registeringPluginIds.add(n);try{let o=t.apiVersion;if(o!==2)throw Error(`Unsupported browser plugin API version for ${r}: ${String(o)} (expected 2)`);let s=t.activate(Object.freeze({apiVersion:2,pluginId:r,runtimePluginId:n,html:g,svg:Ye})).contributions,c=new Set,l=(s.actions??[]).map(t=>this.qualifyAction(n,t,e.machineId,e.sourcePluginId,c)),u=(s.workspacePanels??[]).map(t=>this.qualifyWorkspacePanel(n,t,e.machineId,e.sourcePluginId,a,c)),d=(s.workspaceLabels??[]).map(t=>this.qualifyWorkspaceLabelContribution(n,t,e.machineId,e.sourcePluginId,a,c)),f=e.machineId===void 0?(s.themes??[]).map(e=>this.qualifyTheme(n,e,c)):[],p=e.machineId===void 0?(s.themePairs??[]).map(e=>this.qualifyThemePair(n,e,c)):[];this.pluginIds.add(n);for(let e of c)this.contributionIds.add(e);this.actions.push(...l),this.workspacePanels.push(...u),this.workspaceLabels.push(...d),this.themes.push(...f),this.themePairs.push(...p),e.machineId===void 0?(this.gatewayPluginIds.add(n),i&&this.gatewayMachineSpecificPluginIds.add(n)):e.sourcePluginId!==void 0&&i&&My(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}finally{this.registeringPluginIds.delete(n)}}}hasPlugin(e){return this.pluginIds.has(e)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Fy(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Ty(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.shortcutAliases!==void 0&&(a.shortcutAliases=[...t.shortcutAliases]),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}resolveWorkspacePanelRouteId(e,t){let n=this.workspacePanels.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)),r=n.find(t=>t.id===e);if(r!==void 0)return r.id;let i=n.filter(t=>t.routeAliases?.includes(e)===!0);if(i.length===1)return i[0]?.id;i.length>1&&console.warn(`Ambiguous PI WEB workspace panel route: ${e}`)}async invalidateWorkspacePanels(e,t){await Promise.all(this.workspacePanels.map(async n=>{if(!(n.onInvalidate===void 0||t!==void 0&&n.id!==t))try{await n.onInvalidate(e)}catch(e){console.warn(`Failed to invalidate PI WEB plugin panel ${n.id}`,e)}}))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r,i){let a=this.qualify(e,t.id,i),o=`${r??e}:${t.id}`,s=this.parseShortcutAliases(a,t.shortcutAliases,o);return{...t,id:a,pluginId:e,localId:t.id,...s.length===0?{}:{shortcutAliases:s},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.badge,c=t.visible,l=t.onInvalidate,u=jy(e,r,i),d=`${r??e}:${t.id}`,f=this.parseRouteAliases(o,t.routeAliases,d);return{...t,id:o,pluginId:e,localId:t.id,...f.length===0?{}:{routeAliases:f},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(c?.(Ey(t,u))??!0),...s===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?s(Ey(t,u)):void 0},...l===void 0?{}:{onInvalidate:t=>this.isContributionActive(e,n,t.machine.id,r)?l(Ey(t,u)):void 0},render:e=>t.render(Ey(e,u))}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.visible,c=t.items,l=jy(e,r,i);return{...t,id:o,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(s?.(Dy(t,l))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?c(Dy(t,l)):[]}}qualifyTheme(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id}}qualifyThemePair(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t,n){this.validateLocalId(t);let r=`${e}:${t}`;if(this.contributionIds.has(r)||n.has(r))throw Error(`Duplicate contribution id: ${r}`);return n.add(r),r}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}parseShortcutAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!Ny(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(Ny)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!by.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}validatePluginId(e){if(!_y.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!vy.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return $o(t)}catch{throw Error(`Invalid plugin backend revision for ${e}`)}}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Py(t)}`);return t}};function Ty(e,t){return xy.get(e)?.(t)??e}function Ey(e,t){return Sy.get(e)?.(t)??e}function Dy(e,t){return Cy.get(e)?.(t)??e}function Oy(e,t){return xy.set(e,t),e}function ky(e,t){return Sy.set(e,t),e}function Ay(e,t){return Cy.set(e,t),e}function jy(e,t,n){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n}})}function My(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Ny(e){return yy.test(e)}function Py(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e==null)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Fy(e){return e.state.selectedMachine?.id??`local`}function Iy(e,t,n,r=cs){let i=e.backendRevision;if(i!==void 0)return{request:(a,o)=>r({pluginId:e.sourcePluginId,backendRevision:i,machineId:n,projectId:t.projectId,workspaceId:t.id},a,o)}}function Ly(e,t,n,r){return{readFile:r=>e.workspaceFile(t.projectId,t.id,r,n),listFiles:r=>e.workspaceTree(t.projectId,t.id,r,n),writeFile:async(i,a,o)=>{let s=await e.writeWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s},deleteFile:async i=>{let a=await e.deleteWorkspaceFile(t.projectId,t.id,i,n);return r?.(),a},moveFile:async(i,a,o)=>{let s=await e.moveWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s}}}var Ry=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function zy(){return typeof window>`u`||!(`matchMedia`in window)?[]:Ry.map(e=>window.matchMedia(e))}function By(e,t=Vy()){return e.some(e=>e.matches)||Hy(t)}function Vy(){return typeof navigator>`u`?void 0:navigator}function Hy(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Uy=class{constructor(e=Wy()){this.scheduler=e}repair(e){if(!e){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},250)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);let e=this.scheduler.documentElement;e!==void 0&&(e.scrollTop=0);let t=this.scheduler.body;t!==void 0&&(t.scrollTop=0)}};function Wy(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>`u`?void 0:document.documentElement},get body(){return typeof document>`u`?void 0:document.body}}}var Gy=`(max-width: 760px)`,Ky=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=By(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??qy(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??zy(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Uy,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=By(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(e={}){return Jy(this.isMobileNavigationLayout,e)}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function qy(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(Gy)}function Jy(e,t){return e&&(t.sessionId??``)===``?`navigation`:`chat`}var Yy=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new bc,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Xy(),this.documentTarget=t.documentTarget??Zy(),this.isDocumentVisible=t.isDocumentVisible??Qy,this.scheduleFrame=t.scheduleFrame??$y}connect(){this.connected||(this.connected=!0,this.windowTarget?.addEventListener(`focus`,this.onFocus),this.documentTarget?.addEventListener(`visibilitychange`,this.onVisibilityChange))}disconnect(){this.connected&&(this.connected=!1,this.windowTarget?.removeEventListener(`focus`,this.onFocus),this.documentTarget?.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.scheduledRefresh?.cancel(),this.scheduledRefresh=void 0)}handleResumeSignal(){this.callbacks.onResumeSignal(),this.scheduledRefresh===void 0&&(this.scheduledRefresh=this.scheduleFrame(()=>{this.scheduledRefresh=void 0,this.connected&&this.refreshes.request(`browser-resume`,async()=>{this.connected&&await this.callbacks.refreshAfterResume()}).catch(e=>{this.callbacks.onRefreshError(e)})}))}};function Xy(){return typeof window>`u`?void 0:window}function Zy(){return typeof document>`u`?void 0:document}function Qy(){return typeof document>`u`||document.visibilityState===`visible`}function $y(e){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){let t=window.requestAnimationFrame(()=>{e()});return{cancel:()=>{window.cancelAnimationFrame(t)}}}let t=globalThis.setTimeout(e,0);return{cancel:()=>{globalThis.clearTimeout(t)}}}var eb=[`machines`,`projects`,`workspaces`,`sessions`];function tb(e){return e.selectedWorkspace===void 0?e.selectedProject===void 0?`projects`:`workspaces`:`sessions`}function nb(e,t){if(e!==`none`)return e??tb(t)}function rb(e,t){return nb(t.expanded,t.state)!==e}function ib(e,t,n){return nb(e,n.state)===t?`none`:t}function ab(e){return e.workspaceCount===1?`sessions`:`workspaces`}function ob(e){return eb[eb.indexOf(e)+1]}var sb=class{hostConnected(){}constructor(e,t){this.host=e,this.getState=t,e.addController(this)}expandedSection(){return nb(this.expanded,this.getState())}isCollapsed(e){return rb(e,{expanded:this.expanded,state:this.getState()})}toggle(e){this.setExpanded(ib(this.expanded,e,{state:this.getState()}))}expand(e){this.setExpanded(e)}advanceAfterSelection(e,t){let n=e===`projects`?ab({workspaceCount:t?.workspaceCount}):ob(e);n!==void 0&&this.expand(n)}open(e,t){this.expand(e),t()}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}},cb=class{hostConnected(){}constructor(e){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this)}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(e,t=!0){return[`shell`,ub(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...lb(this.workspacePanelCollapsed,t)?[]:[`workspace-panel-collapsed`]].join(` `)}};function lb(e,t){return!e&&t}function ub(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var db=`pi-web:panel-sizes:v1`,fb={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},pb=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??Db(),this.panelSizes=yb(this.storage)}hostConnected(){}constraints(e){return mb(e)}panelWidth(e,t){return vb(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=vb(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Cb(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=wb(this.panelSizes,e),t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(e={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},e.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){bb(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${Eb(vb(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${Eb(vb(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function mb(e){return fb[e]}function hb(e,t,n){return e===`navigation`?n-t:t-n}function gb(e,t,n,r,i=mb(e)){return vb(e,t+hb(e,n,r),i)}function _b(e,t,n,r={}){let i=r.constraints??mb(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=Tb(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return vb(e,t+a,i)}function vb(e,t,n=mb(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function yb(e=Db()){try{let t=e?.getItem(db);return t==null||t===``?{}:xb(JSON.parse(t))}catch{return{}}}function bb(e,t=Db()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(db);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=vb(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=vb(`workspace`,e.workspacePanelWidth)),t.setItem(db,JSON.stringify(n))}catch{}}function xb(e){if(!Ob(e)||e.version!==1)return{};let t={},n=Sb(e.navigationPanelWidth),r=Sb(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=vb(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=vb(`workspace`,r)),t}function Sb(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Cb(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function wb(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Tb(e,t,n){if(e===`navigation`)return t===`ArrowRight`?n:t===`ArrowLeft`?-n:void 0;if(t===`ArrowLeft`)return n;if(t===`ArrowRight`)return-n}function Eb(e){return`${String(Math.round(e))}px`}function Db(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function Ob(e){return typeof e==`object`&&!!e}function kb(){let e=new URLSearchParams(window.location.search);return{machineId:Nb(e.get(`machine`)),projectId:Nb(e.get(`project`)),workspaceId:Nb(e.get(`workspace`)),sessionId:Nb(e.get(`session`)),tool:Nb(e.get(`tool`)),view:Nb(e.get(`view`))}}function Ab(e,t){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool===void 0?void 0:jb(e.tool,t),view:e.view===`chat`?`chat`:e.view===void 0?void 0:jb(e.view,t)}}function jb(e,t){return t(e)??(Pb(e)?e:void 0)}function Mb(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&e.tool!==``&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&e.view!==``&&n.searchParams.set(`view`,e.view),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function Nb(e){return e===null||e===``?void 0:e}function Pb(e){return/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Fb(){return Lb(new URLSearchParams(window.location.search).get(`settings`))}function Ib(e,t){let n=new URL(window.location.href);e===void 0?n.searchParams.delete(`settings`):n.searchParams.set(`settings`,e),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function Lb(e){if(e===`general`)return`general`;if(e===`appearance`||e===`theme`||e===`themes`)return`appearance`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`machines`)return`machines`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function Rb(e,t){return t===void 0?e:e.map(e=>Bb(e,t))}function zb(e,t){let n=new Set(Wp(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return Rb(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?Vb(e):e)}function Bb(e,t){let n=Zp(e,t);return n===void 0?e:n===null?Vb(e):{...e,shortcut:n}}function Vb(e){let t={...e};return delete t.shortcut,t}function Hb(e,t){let n=t.api??No,r=t.pollIntervalMs??1e3,i=t.setTimeout??Gb(),a=t.clearTimeout??Kb();return{async runCommand(o){let s=await n.runTerminalCommand(e,o);return o.open===!0&&t.openTerminal(o.workspace,{terminalId:s.terminalId}),{run:s,completed:Ub(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Ub(e,t,n,r,i){return Wb(e)?Promise.resolve(e):new Promise((a,o)=>{let s,c=!1,l=e=>{c||(c=!0,s!==void 0&&i(s),a(e))},u=e=>{c||(c=!0,s!==void 0&&i(s),o(e instanceof Error?e:Error(String(e))))},d=()=>{t.getCommandRun(e.id).then(e=>{if(e!==void 0&&Wb(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function Wb(e){return e.status===`succeeded`||e.status===`failed`}function Gb(){return(e,t)=>globalThis.setTimeout(e,t)}function Kb(){return e=>{globalThis.clearTimeout(e)}}var qb=class{constructor(e){this.callbacks=e,this.fired=!1}start(e){this.cancel(),this.origin=e,this.fired=!1,this.handle=this.callbacks.setTimer(()=>{this.handle=void 0,this.fired=!0,this.callbacks.onLongPress()},500)}move(e){if(this.origin===void 0)return;let t=Math.abs(e.clientX-this.origin.clientX),n=Math.abs(e.clientY-this.origin.clientY);(t>10||n>10)&&this.cancel()}cancel(){this.handle!==void 0&&this.callbacks.clearTimer(this.handle),this.handle=void 0,this.origin=void 0}consumeSuppressedClick(){let e=this.fired;return this.fired=!1,e}},Jb=class{constructor(e){this.open=e,this.longPress=new qb({onLongPress:()=>{this.heldId!==void 0&&this.open(this.heldId,this.heldAnchor??null)},setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>{window.clearTimeout(e)}})}pointerDown(e,t){t.pointerType!==`mouse`&&(this.heldId=e,this.heldAnchor=t.currentTarget,this.longPress.start(t))}pointerMove(e){this.longPress.move(e)}cancel(){this.longPress.cancel(),this.heldId=void 0,this.heldAnchor=void 0}consumeSuppressedClick(){return this.longPress.consumeSuppressedClick()}contextMenu(e,t){t.preventDefault(),this.open(e,t.currentTarget)}},Yb=0,Xb=120;function Zb(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?$b():Qb(e),i=window.innerWidth,a=window.innerHeight,o=Math.max(0,r.left),s=Math.min(i,r.right),c=Math.max(0,r.top),l=Math.min(a,r.bottom),u=Math.min(n.right,s),d=l-n.bottom-Yb,f=n.top-c-Yb;return[...d<Xb&&f>d?[`bottom: ${ex(a-n.top+Yb)};`,`max-height: ${ex(Math.max(0,f))};`]:[`top: ${ex(n.bottom+Yb)};`,`max-height: ${ex(Math.max(0,d))};`],`right: ${ex(Math.max(0,i-u))};`,`max-width: ${ex(Math.max(0,u-o))};`].join(` `)}function Qb(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():$b()}function $b(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function ex(e){return`${String(Math.round(e))}px`}function tx(e,t=`Active`,n){if(e===void 0)return n===void 0?void 0:g`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function nx(e){if(e!==void 0)return e[zt.working]===!0?`session`:e[zt.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==zt.unread)?`session`:void 0}function rx(e){return e?.[zt.unread]===!0}var ix={working:`Session is working`,idle:`Session is done`,asking:`Waiting for your answer`,error:`Session hit an error`};function ax(e,t){if(e===void 0)return t===void 0?void 0:g`<span class="session-state unread" role="img" aria-label=${t} title=${t}></span>`;let n=e===`sending`?`Sending message`:ix[e],r=t===void 0?n:`${t} · ${n}`;if(e===`idle`)return g`<span class=${t===void 0?`session-state idle`:`session-state idle unread`} role="img" aria-label=${r} title=${r}></span>`;if(e===`working`||e===`sending`){let i=e===`working`?[0,1,2].map(e=>g`<span class="state-dot working-dot" style=${`animation-delay:${(e*.14).toFixed(2)}s`}></span>`):null;return t===void 0?g`<span class="session-state working" role="img" aria-label=${n} title=${n}><span class="state-dots">${i}</span></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class="session-state working" aria-hidden="true"><span class="state-dots">${i}</span></span></span>`}return t===void 0?g`<span class=${`session-state ${e}`} role="img" aria-label=${n} title=${n}></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`session-state ${e}`} aria-hidden="true"></span></span>`}function ox(e,t=`Active`,n){let r=tx(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var sx=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function cx(e){return e.composedPath().some(e=>lx(e,sx))}function lx(e,t){if(typeof Element<`u`&&e instanceof Element)return e.matches(t);if(!(`matches`in e))return!1;let{matches:n}=e;return typeof n==`function`&&n.call(e,t)===!0}function ux(e,t){return cx(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?fx(e,()=>{px(e.currentTarget,-1)}):e.key===`ArrowDown`?fx(e,()=>{px(e.currentTarget,1)}):e.key===`Home`?fx(e,()=>{mx(e.currentTarget,0)}):e.key===`End`?fx(e,()=>{mx(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?fx(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?fx(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&fx(e,t.cancel)}function dx(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n==null?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function fx(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function px(e,t){let n=gx(e),r=vx(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||hx(n,i+t)}function mx(e,t){let n=gx(e);n.length!==0&&hx(n,t<0?n.length-1:t)}function hx(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function gx(e){let t=vx(e)?.getRootNode();return t===void 0||!_x(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function _x(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function vx(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var U=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.gestures=new Jb((e,t)=>{this.openMenu(e,t)}),this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.openMenuMachineId!==void 0&&!this.machines.some(e=>e.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,dx(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
1358
1371
  <section>
1359
1372
  <h2>${this.renderHeading()}${this.renderAdd()}</h2>
1360
1373
  ${this.collapsed?null:g`
@@ -2224,9 +2237,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2224
2237
  .custom-focus, .validation-error { margin-inline-start: 0; }
2225
2238
  footer { flex-wrap: wrap; }
2226
2239
  }
2227
- `}};H([b({attribute:!1})],MS.prototype,`tree`,void 0),H([b({attribute:!1})],MS.prototype,`onNavigate`,void 0),H([b({attribute:!1})],MS.prototype,`onFork`,void 0),H([b({attribute:!1})],MS.prototype,`onAbort`,void 0),H([b({attribute:!1})],MS.prototype,`onCancel`,void 0),H([x()],MS.prototype,`selectedId`,void 0),H([x()],MS.prototype,`foldedIds`,void 0),H([x()],MS.prototype,`step`,void 0),H([x()],MS.prototype,`operation`,void 0),H([x()],MS.prototype,`summaryMode`,void 0),H([x()],MS.prototype,`customInstructions`,void 0),H([x()],MS.prototype,`busy`,void 0),H([x()],MS.prototype,`aborting`,void 0),H([x()],MS.prototype,`error`,void 0),H([x()],MS.prototype,`statusMessage`,void 0),MS=H([y(`session-tree-navigator`)],MS);function NS(e){return Math.min(Math.max(0,e),AS)}function PS(e){return e===`user`||e===`custom-message`}function FS(e){return jS[e]}function IS(e){return e instanceof Error?e.message:String(e)}var{I:LS}=ut,RS=e=>e,zS=()=>document.createComment(``),BS=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new LS(r.insertBefore(zS(),i),r.insertBefore(zS(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=RS(e).nextSibling;RS(r).insertBefore(e,i),e=t}}}return n},VS=(e,t,n=e)=>(e._$AI(t,n),e),HS={},US=(e,t=HS)=>e._$AH=t,WS=e=>e._$AH,GS=e=>{e._$AR(),e._$AA.remove()},KS=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},qS=fg(class extends pg{constructor(e){if(super(e),e.type!==dg.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=WS(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,d=0,f=i.length-1,p=0,m=a.length-1;for(;d<=f&&p<=m;)if(i[d]===null)d++;else if(i[f]===null)f--;else if(s[d]===o[p])c[p]=VS(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=VS(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=VS(i[d],a[m]),BS(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=VS(i[f],a[p]),BS(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=KS(o,p,m),u=KS(s,d,f)),l.has(s[d]))if(l.has(s[f])){let t=u.get(o[p]),n=t===void 0?null:i[t];if(n===null){let t=BS(e,i[d]);VS(t,a[p]),c[p]=t}else c[p]=VS(n,a[p]),BS(e,i[d],n),i[t]=null;p++}else GS(i[f]),f--;else GS(i[d]),d++;for(;p<=m;){let t=BS(e,c[m+1]);VS(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&GS(e)}return this.ut=o,US(e,c),Xe}}),JS=`pi-web:chat-groups:`,YS={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(ZS(e));return t===null||t===``?void 0:QS(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(ZS(e),JSON.stringify(t))}catch{}}},XS=class{constructor(e=YS){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&&eC(i,this.openGroupKeys)&&eC(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 ZS(e){return`${JS}${e}`}function QS(e){if(Array.isArray(e))return{open:$S(e),closedDefaultOpen:[]};if(tC(e))return{open:Array.isArray(e.open)?$S(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?$S(e.closedDefaultOpen):[]}}function $S(e){return e.filter(e=>typeof e==`string`)}function eC(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function tC(e){return typeof e==`object`&&!!e}function nC(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=>oC(e,t)),s=e.parts.filter(t=>!oC(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}};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,...l};if(iC(t)){let e=aC(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 rC(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 iC(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function aC(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function oC(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`askUserRecord`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}function sC(e,t,n){let r=e.length;if(r===0||t.length===0||n.length!==r+1||n[r-1]!==e[r-1])return;let i=n[r],a=e[r-1];if(i===void 0||a===void 0)return;let o=t.at(-1);if(o===void 0)return;let s=t.slice(0,-1),c,l;o.kind===`group`?(c=o.startIndex,l=[...o.messages,i]):(c=o.index,l=[a,i]);let u=nC(l,c);return[...s,...u]}function cC(e,t){let n=uC(pC(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function lC(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=dC(r,t.markerOffset);return}e.scrollTop=fC(e.scrollHeight,t.distanceFromBottom)}function uC(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 dC(e,t){return e-t}function fC(e,t){return Math.max(0,e-t)}function pC(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 mC=600,hC=1;function gC(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:_C(e)||vC(e)}function _C(e){return e.scrollTop<(e.topThreshold??Math.max(mC,e.clientHeight))}function vC(e){return e.scrollHeight<=e.clientHeight+hC}var yC=`pi-web:chat-scroll:`,bC=180,xC=48,SC=2,CC={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)}},wC={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},TC=class{constructor(e=CC,t=wC){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=bC){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=SC){if(e===``||t===void 0||!OC(t))return`skipped`;try{if(AC(t,r))return this.storage.setItem(EC(e),JSON.stringify({mode:`bottom`})),`saved`;let i=MC(t,n);if(i===void 0)return`skipped`;let a=jC(t,i);return this.storage.setItem(EC(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||!OC(t))return{status:`skipped`};let i=PC(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(EC(e));if(t===null||t===``)return;let n=JSON.parse(t);return DC(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!OC(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function EC(e){return`${yC}${e}`}function DC(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 OC(e){return e.clientHeight>0&&e.scrollHeight>0}function kC(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function AC(e,t=xC){return kC(e)<t}function jC(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:FC(t)??``,offset:t.getBoundingClientRect().top-n}}function MC(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(FC(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 NC(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function PC(e,t){return e.find(e=>FC(e)===t)}function FC(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var IC={left:!1,right:!1},LC=1;function RC(e){if(e===void 0)return IC;let t=Math.max(0,e.scrollWidth-e.clientWidth);return{left:e.scrollLeft>LC,right:t-e.scrollLeft>LC}}function zC(e){return`${e.left?` can-scroll-left`:``}${e.right?` can-scroll-right`:``}`}var BC=e=>{if(!(typeof ResizeObserver>`u`))return new ResizeObserver(()=>{e()})},VC=class{constructor(e,t=BC){this.onChange=e,this.createObserver=t,this.current=IC}get edges(){return this.current}observe(e){if(this.element!==e&&(this.observer?.disconnect(),this.observer=void 0,this.element=e,e!==void 0)){let t=this.createObserver(()=>{this.refresh()});t!==void 0&&(t.observe(e),this.observer=t)}this.refresh()}refresh(){let e=RC(this.element);e.left===this.current.left&&e.right===this.current.right||(this.current=e,this.onChange())}dispose(){this.observer?.disconnect(),this.observer=void 0,this.element=void 0,this.current=IC}};function HC(e){return e.role===`user`&&UC(e)!==void 0}function UC(e){if(e.role!==`user`)return;let t=[],n=[];for(let r of e.parts){if(WC(r)){r.text!==``&&t.push(r.text);continue}r.type===`image`&&r.data!==``&&r.mimeType!==``&&n.push({kind:`image`,mimeType:r.mimeType,data:r.data})}let r=t.join(`
2240
+ `}};H([b({attribute:!1})],MS.prototype,`tree`,void 0),H([b({attribute:!1})],MS.prototype,`onNavigate`,void 0),H([b({attribute:!1})],MS.prototype,`onFork`,void 0),H([b({attribute:!1})],MS.prototype,`onAbort`,void 0),H([b({attribute:!1})],MS.prototype,`onCancel`,void 0),H([x()],MS.prototype,`selectedId`,void 0),H([x()],MS.prototype,`foldedIds`,void 0),H([x()],MS.prototype,`step`,void 0),H([x()],MS.prototype,`operation`,void 0),H([x()],MS.prototype,`summaryMode`,void 0),H([x()],MS.prototype,`customInstructions`,void 0),H([x()],MS.prototype,`busy`,void 0),H([x()],MS.prototype,`aborting`,void 0),H([x()],MS.prototype,`error`,void 0),H([x()],MS.prototype,`statusMessage`,void 0),MS=H([y(`session-tree-navigator`)],MS);function NS(e){return Math.min(Math.max(0,e),AS)}function PS(e){return e===`user`||e===`custom-message`}function FS(e){return jS[e]}function IS(e){return e instanceof Error?e.message:String(e)}var LS=`pi-web:chat-scroll:`,RS=180,zS=48,BS=2,VS={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)}},HS={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},US=class{constructor(e=VS,t=HS){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=RS){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=BS){if(e===``||t===void 0||!KS(t))return`skipped`;try{if(JS(t,r))return this.storage.setItem(WS(e),JSON.stringify({mode:`bottom`})),`saved`;let i=XS(t,n);if(i===void 0)return`skipped`;let a=YS(t,i);return this.storage.setItem(WS(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||!KS(t))return{status:`skipped`};let i=QS(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(WS(e));if(t===null||t===``)return;let n=JSON.parse(t);return GS(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!KS(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function WS(e){return`${LS}${e}`}function GS(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 KS(e){return e.clientHeight>0&&e.scrollHeight>0}function qS(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function JS(e,t=zS){return qS(e)<t}function YS(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:$S(t)??``,offset:t.getBoundingClientRect().top-n}}function XS(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if($S(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 ZS(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function QS(e,t){return e.find(e=>$S(e)===t)}function $S(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}function eC(e){return qS(e)>=e.clientHeight*1}var{I:tC}=ut,nC=e=>e,rC=()=>document.createComment(``),iC=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new tC(r.insertBefore(rC(),i),r.insertBefore(rC(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=nC(e).nextSibling;nC(r).insertBefore(e,i),e=t}}}return n},aC=(e,t,n=e)=>(e._$AI(t,n),e),oC={},sC=(e,t=oC)=>e._$AH=t,cC=e=>e._$AH,lC=e=>{e._$AR(),e._$AA.remove()},uC=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},dC=fg(class extends pg{constructor(e){if(super(e),e.type!==dg.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=cC(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,d=0,f=i.length-1,p=0,m=a.length-1;for(;d<=f&&p<=m;)if(i[d]===null)d++;else if(i[f]===null)f--;else if(s[d]===o[p])c[p]=aC(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=aC(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=aC(i[d],a[m]),iC(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=aC(i[f],a[p]),iC(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=uC(o,p,m),u=uC(s,d,f)),l.has(s[d]))if(l.has(s[f])){let t=u.get(o[p]),n=t===void 0?null:i[t];if(n===null){let t=iC(e,i[d]);aC(t,a[p]),c[p]=t}else c[p]=aC(n,a[p]),iC(e,i[d],n),i[t]=null;p++}else lC(i[f]),f--;else lC(i[d]),d++;for(;p<=m;){let t=iC(e,c[m+1]);aC(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&lC(e)}return this.ut=o,sC(e,c),Xe}}),fC=`pi-web:chat-groups:`,pC={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(hC(e));return t===null||t===``?void 0:gC(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(hC(e),JSON.stringify(t))}catch{}}},mC=class{constructor(e=pC){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&&vC(i,this.openGroupKeys)&&vC(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 hC(e){return`${fC}${e}`}function gC(e){if(Array.isArray(e))return{open:_C(e),closedDefaultOpen:[]};if(yC(e))return{open:Array.isArray(e.open)?_C(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?_C(e.closedDefaultOpen):[]}}function _C(e){return e.filter(e=>typeof e==`string`)}function vC(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function yC(e){return typeof e==`object`&&!!e}function bC(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=>wC(e,t)),s=e.parts.filter(t=>!wC(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}};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,...l};if(SC(t)){let e=CC(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 xC(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 SC(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function CC(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function wC(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`askUserRecord`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}function TC(e,t,n){let r=e.length;if(r===0||t.length===0||n.length!==r+1||n[r-1]!==e[r-1])return;let i=n[r],a=e[r-1];if(i===void 0||a===void 0)return;let o=t.at(-1);if(o===void 0)return;let s=t.slice(0,-1),c,l;o.kind===`group`?(c=o.startIndex,l=[...o.messages,i]):(c=o.index,l=[a,i]);let u=bC(l,c);return[...s,...u]}function EC(e,t){let n=OC(jC(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function DC(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=kC(r,t.markerOffset);return}e.scrollTop=AC(e.scrollHeight,t.distanceFromBottom)}function OC(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 kC(e,t){return e-t}function AC(e,t){return Math.max(0,e-t)}function jC(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 MC=600,NC=1;function PC(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:FC(e)||IC(e)}function FC(e){return e.scrollTop<(e.topThreshold??Math.max(MC,e.clientHeight))}function IC(e){return e.scrollHeight<=e.clientHeight+NC}var LC={left:!1,right:!1},RC=1;function zC(e){if(e===void 0)return LC;let t=Math.max(0,e.scrollWidth-e.clientWidth);return{left:e.scrollLeft>RC,right:t-e.scrollLeft>RC}}function BC(e){return`${e.left?` can-scroll-left`:``}${e.right?` can-scroll-right`:``}`}var VC=e=>{if(!(typeof ResizeObserver>`u`))return new ResizeObserver(()=>{e()})},HC=class{constructor(e,t=VC){this.onChange=e,this.createObserver=t,this.current=LC}get edges(){return this.current}observe(e){if(this.element!==e&&(this.observer?.disconnect(),this.observer=void 0,this.element=e,e!==void 0)){let t=this.createObserver(()=>{this.refresh()});t!==void 0&&(t.observe(e),this.observer=t)}this.refresh()}refresh(){let e=zC(this.element);e.left===this.current.left&&e.right===this.current.right||(this.current=e,this.onChange())}dispose(){this.observer?.disconnect(),this.observer=void 0,this.element=void 0,this.current=LC}};function UC(e){return e.role===`user`&&WC(e)!==void 0}function WC(e){if(e.role!==`user`)return;let t=[],n=[];for(let r of e.parts){if(GC(r)){r.text!==``&&t.push(r.text);continue}r.type===`image`&&r.data!==``&&r.mimeType!==``&&n.push({kind:`image`,mimeType:r.mimeType,data:r.data})}let r=t.join(`
2228
2241
 
2229
- `).trim();if(!(r===``&&n.length===0))return{text:r,attachments:n}}function WC(e){return e.type===`text`}function GC(e){return e.status===`complete`||e.status===`completed`||e.status===`abandoned`}function KC(e){return e.status===`paused`||e.status===`blocked`||e.status===`budget_limited`}function qC(e){return e.totalTaskCount<=0?0:Math.min(1,Math.max(0,e.completedTaskCount/e.totalTaskCount))}function JC(e){return e.totalTaskCount<=0?`No tasks`:`${String(e.completedTaskCount)}/${String(e.totalTaskCount)}`}function YC(e){switch(e){case`active`:return`Active`;case`paused`:return`Paused`;case`blocked`:return`Blocked`;case`complete`:case`completed`:return`Complete`;case`abandoned`:return`Abandoned`;case`budget_limited`:return`Budget reached`;default:return e.replace(/_/gu,` `)}}function XC(e){if(e.currentTaskId!==void 0)return ZC(e.tasks,e.currentTaskId)}function ZC(e,t){for(let n of e){if(n.id===t)return n;let e=n.subtasks===void 0?void 0:ZC(n.subtasks,t);if(e!==void 0)return e}}function QC(e,t=0){let n=[];for(let r of e)n.push({task:r,depth:t}),r.subtasks!==void 0&&n.push(...QC(r.subtasks,t+1));return n}function $C(e){if(!(e===void 0||e<=0))return e>=1e6?`${(e/1e6).toFixed(1)}M tokens`:e>=1e3?`${String(Math.round(e/1e3))}k tokens`:`${String(e)} tokens`}function ew(e){if(GC(e))return[];let t=KC(e)?[{label:`Resume`,command:`/goal-resume`,description:`Resume this goal in the focused session`,destructive:!1}]:[{label:`Pause`,command:`/goal-pause`,description:`Pause this goal`,destructive:!1}];return t.push({label:`Abandon`,command:`/goal-clear`,description:`Archive this goal after confirmation`,destructive:!0}),t}var tw=class extends v{constructor(...e){super(...e),this.goals=[],this.loading=!1,this.canRunCommands=!0,this.expanded=new Set}render(){return g`
2242
+ `).trim();if(!(r===``&&n.length===0))return{text:r,attachments:n}}function GC(e){return e.type===`text`}function KC(e){return e.status===`complete`||e.status===`completed`||e.status===`abandoned`}function qC(e){return e.status===`paused`||e.status===`blocked`||e.status===`budget_limited`}function JC(e){return e.totalTaskCount<=0?0:Math.min(1,Math.max(0,e.completedTaskCount/e.totalTaskCount))}function YC(e){return e.totalTaskCount<=0?`No tasks`:`${String(e.completedTaskCount)}/${String(e.totalTaskCount)}`}function XC(e){switch(e){case`active`:return`Active`;case`paused`:return`Paused`;case`blocked`:return`Blocked`;case`complete`:case`completed`:return`Complete`;case`abandoned`:return`Abandoned`;case`budget_limited`:return`Budget reached`;default:return e.replace(/_/gu,` `)}}function ZC(e){if(e.currentTaskId!==void 0)return QC(e.tasks,e.currentTaskId)}function QC(e,t){for(let n of e){if(n.id===t)return n;let e=n.subtasks===void 0?void 0:QC(n.subtasks,t);if(e!==void 0)return e}}function $C(e,t=0){let n=[];for(let r of e)n.push({task:r,depth:t}),r.subtasks!==void 0&&n.push(...$C(r.subtasks,t+1));return n}function ew(e){if(!(e===void 0||e<=0))return e>=1e6?`${(e/1e6).toFixed(1)}M tokens`:e>=1e3?`${String(Math.round(e/1e3))}k tokens`:`${String(e)} tokens`}function tw(e){if(KC(e))return[];let t=qC(e)?[{label:`Resume`,command:`/goal-resume`,description:`Resume this goal in the focused session`,destructive:!1}]:[{label:`Pause`,command:`/goal-pause`,description:`Pause this goal`,destructive:!1}];return t.push({label:`Abandon`,command:`/goal-clear`,description:`Archive this goal after confirmation`,destructive:!0}),t}var nw=class extends v{constructor(...e){super(...e),this.goals=[],this.loading=!1,this.canRunCommands=!0,this.expanded=new Set}render(){return g`
2230
2243
  <section>
2231
2244
  <h2>
2232
2245
  Goals
@@ -2242,7 +2255,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2242
2255
  </h2>
2243
2256
  ${this.goals.length===0?this.renderEmpty():g`<div class="goal-list">${this.goals.map(e=>this.renderGoal(e))}</div>`}
2244
2257
  </section>
2245
- `}openGoalsLabel(){let e=this.goals.filter(e=>!GC(e)).length;return e===0?``:`${String(e)} open`}renderCommands(e){let t=ew(e);return t.length===0?null:g`
2258
+ `}openGoalsLabel(){let e=this.goals.filter(e=>!KC(e)).length;return e===0?``:`${String(e)} open`}renderCommands(e){let t=tw(e);return t.length===0?null:g`
2246
2259
  <div class="goal-commands">
2247
2260
  ${t.map(t=>g`
2248
2261
  <button
@@ -2254,7 +2267,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2254
2267
  >${t.label}</button>
2255
2268
  `)}
2256
2269
  </div>
2257
- `}renderEmpty(){return g`<p class="empty">${this.loading?`Loading goals…`:`No goals recorded for this workspace.`}</p>`}renderGoal(e){let t=this.expanded.has(e.id),n=qC(e),r=$C(e.tokensUsed),i=XC(e),a=GC(e)?`done`:KC(e)?`blocked`:`active`;return g`
2270
+ `}renderEmpty(){return g`<p class="empty">${this.loading?`Loading goals…`:`No goals recorded for this workspace.`}</p>`}renderGoal(e){let t=this.expanded.has(e.id),n=JC(e),r=ew(e.tokensUsed),i=ZC(e),a=KC(e)?`done`:qC(e)?`blocked`:`active`;return g`
2258
2271
  <article class=${`goal ${a}`}>
2259
2272
  <button
2260
2273
  class="goal-header"
@@ -2265,8 +2278,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2265
2278
  >
2266
2279
  <span class="goal-caret" aria-hidden="true">${t?`▾`:`▸`}</span>
2267
2280
  <span class="goal-objective">${e.objective}</span>
2268
- <span class=${`goal-status ${a}`}>${YC(e.status)}</span>
2269
- <span class="goal-ratio">${JC(e)}</span>
2281
+ <span class=${`goal-status ${a}`}>${XC(e.status)}</span>
2282
+ <span class="goal-ratio">${YC(e)}</span>
2270
2283
  </button>
2271
2284
  <div
2272
2285
  class="goal-bar"
@@ -2274,7 +2287,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2274
2287
  aria-valuemin="0"
2275
2288
  aria-valuemax=${String(e.totalTaskCount)}
2276
2289
  aria-valuenow=${String(e.completedTaskCount)}
2277
- aria-label=${`${e.objective}: ${JC(e)} tasks complete`}
2290
+ aria-label=${`${e.objective}: ${YC(e)} tasks complete`}
2278
2291
  >
2279
2292
  <span class="goal-bar-fill" style=${`transform: scaleX(${String(n)})`}></span>
2280
2293
  </div>
@@ -2287,7 +2300,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2287
2300
  ${r===void 0?_:g`<span class="goal-reason">${r}</span>`}
2288
2301
  ${n===void 0?_:g`<span class="goal-tokens">${n}</span>`}
2289
2302
  </p>
2290
- `}renderDetail(e,t,n){let r=QC(e.tasks);return g`
2303
+ `}renderDetail(e,t,n){let r=$C(e.tasks);return g`
2291
2304
  <div class="goal-detail">
2292
2305
  ${e.pauseReason===void 0?_:g`<p class="goal-reason detail">${e.pauseReason}</p>`}
2293
2306
  ${e.verificationContract===void 0?_:g`<p class="goal-contract"><span class="label">Verification</span>${e.verificationContract}</p>`}
@@ -2396,7 +2409,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2396
2409
  @container (max-width: 580px) {
2397
2410
  .goal-header, .refresh-entry { min-height: 42px; }
2398
2411
  }
2399
- `]}};H([b({attribute:!1})],tw.prototype,`goals`,void 0),H([b({type:Boolean})],tw.prototype,`loading`,void 0),H([b({attribute:!1})],tw.prototype,`onRefresh`,void 0),H([b({attribute:!1})],tw.prototype,`onArchive`,void 0),H([b({attribute:!1})],tw.prototype,`onRunCommand`,void 0),H([b({type:Boolean})],tw.prototype,`canRunCommands`,void 0),H([x()],tw.prototype,`expanded`,void 0),H([x()],tw.prototype,`confirmingArchiveId`,void 0),tw=H([y(`goal-panel`)],tw);function nw(e){let t=e?.trim();if(t===void 0||t===``)return;let n=t.indexOf(`/`),r=n===-1?void 0:t.slice(0,n),i=n===-1?t:t.slice(n+1),a=i.lastIndexOf(`:`),o=a===-1?i:i.slice(0,a),s=a===-1?void 0:i.slice(a+1);if(o!==``)return{...r===void 0||r===``?{}:{provider:r},model:o,...s===void 0||s===``?{}:{thinking:s},label:s===void 0||s===``?o:`${o} · ${s}`}}function rw(e){typeof CSS<`u`&&CSS.supports(`field-sizing`,`content`)||(e.style.height=`auto`,e.style.height=`${String(e.scrollHeight)}px`)}var iw=class extends v{constructor(...e){super(...e),this.draftSessionId=``,this.answers={},this.step=0,this.confirmingPartialSubmit=!1,this.submitting=!1}willUpdate(e){if(!e.has(`ask`)&&!e.has(`outcome`)&&!e.has(`draftSessionId`))return;let t=this.currentModelIdentity();t!==this.modelIdentity&&(this.modelIdentity=t,this.answers=this.loadCurrentDraft(),this.confirmingPartialSubmit=!1,this.submitting=!1)}render(){return this.outcome===void 0?this.ask===void 0?null:this.renderOpenAsk(this.ask):this.renderRecord(this.outcome)}renderOpenAsk(e){let t=Hl(e.questions,this.answers),n=Ul(e.questions,this.answers);return g`
2412
+ `]}};H([b({attribute:!1})],nw.prototype,`goals`,void 0),H([b({type:Boolean})],nw.prototype,`loading`,void 0),H([b({attribute:!1})],nw.prototype,`onRefresh`,void 0),H([b({attribute:!1})],nw.prototype,`onArchive`,void 0),H([b({attribute:!1})],nw.prototype,`onRunCommand`,void 0),H([b({type:Boolean})],nw.prototype,`canRunCommands`,void 0),H([x()],nw.prototype,`expanded`,void 0),H([x()],nw.prototype,`confirmingArchiveId`,void 0),nw=H([y(`goal-panel`)],nw);function rw(e){let t=e?.trim();if(t===void 0||t===``)return;let n=t.indexOf(`/`),r=n===-1?void 0:t.slice(0,n),i=n===-1?t:t.slice(n+1),a=i.lastIndexOf(`:`),o=a===-1?i:i.slice(0,a),s=a===-1?void 0:i.slice(a+1);if(o!==``)return{...r===void 0||r===``?{}:{provider:r},model:o,...s===void 0||s===``?{}:{thinking:s},label:s===void 0||s===``?o:`${o} · ${s}`}}function iw(e){typeof CSS<`u`&&CSS.supports(`field-sizing`,`content`)||(e.style.height=`auto`,e.style.height=`${String(e.scrollHeight)}px`)}var aw=class extends v{constructor(...e){super(...e),this.draftSessionId=``,this.answers={},this.step=0,this.confirmingPartialSubmit=!1,this.submitting=!1}willUpdate(e){if(!e.has(`ask`)&&!e.has(`outcome`)&&!e.has(`draftSessionId`))return;let t=this.currentModelIdentity();t!==this.modelIdentity&&(this.modelIdentity=t,this.answers=this.loadCurrentDraft(),this.confirmingPartialSubmit=!1,this.submitting=!1)}render(){return this.outcome===void 0?this.ask===void 0?null:this.renderOpenAsk(this.ask):this.renderRecord(this.outcome)}renderOpenAsk(e){let t=Hl(e.questions,this.answers),n=Ul(e.questions,this.answers);return g`
2400
2413
  <article class="card open-card" aria-labelledby="ask-user-heading">
2401
2414
  <header class="card-header">
2402
2415
  <h2 id="ask-user-heading">Questions</h2>
@@ -2519,7 +2532,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2519
2532
  ${r.fromDraft?g`<p class="draft-note">Draft answer · not sent</p>`:null}
2520
2533
  `}
2521
2534
  </section>
2522
- `}changeOption(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;if(e.multiple!==!0){r.checked&&this.setAnswer(e,{values:[t]});return}let i=this.answers[e.id],a=r.checked?[...new Set([...i?.values??[],t])]:(i?.values??[]).filter(e=>e!==t);this.setAnswer(e,{values:a,...i?.otherText===void 0?{}:{otherText:i.otherText}})}changeOther(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;let i=this.answers[e.id];e.multiple===!0?this.setAnswer(e,{values:[...i?.values??[]],...r.checked?{otherText:i?.otherText??``}:{}}):r.checked&&this.setAnswer(e,{values:[],otherText:this.isOtherSelected(e,i)?i?.otherText??``:``}),r.checked&&this.focusOtherInput(t)}changeOtherText(e,t){let n=t.currentTarget;if(!(n instanceof HTMLTextAreaElement))return;rw(n);let r=this.answers[e.id];this.setAnswer(e,{values:[...r?.values??[]],otherText:n.value.slice(0,Pt)})}setAnswer(e,t){let n=t.values.length===0&&t.otherText===void 0?Object.fromEntries(Object.entries(this.answers).filter(([t])=>t!==e.id)):{...this.answers,[e.id]:t};this.answers=n,this.confirmingPartialSubmit=!1,this.ask!==void 0&&this.draftSessionId!==``&&Rl(this.draftSessionId,this.ask.askId,n)}handleSubmit(e,t){if(e.preventDefault(),!this.submitting){if(Ul(t.questions,this.answers).length>0){this.showPartialSubmitConfirmation();return}this.submitAnswers(t)}}submitAnswers(e){if(this.submitting)return;this.submitting=!0;let t=this.onSubmit;if(t===void 0){this.submitting=!1;return}let n=e.askId;Promise.resolve().then(()=>t(n,Wl(e.questions,this.answers))).catch(()=>{}).finally(()=>{this.ask?.askId===n&&(this.submitting=!1)})}async showPartialSubmitConfirmation(){this.confirmingPartialSubmit=!0,await this.updateComplete,this.renderRoot.querySelector(`.send-anyway`)?.focus()}keepEditing(e,t){this.confirmingPartialSubmit=!1;let n=t[0];n!==void 0&&this.focusQuestion(e.questions.indexOf(n))}focusQuestion(e){e<0||this.updateComplete.then(()=>{let t=this.renderRoot.querySelector(`#${this.questionFieldsetId(e)}`);(t?.querySelector(`input, textarea`)??t)?.focus()})}async focusOtherInput(e){await this.updateComplete,this.renderRoot.querySelector(`#${this.otherInputId(e)}`)?.focus()}isOtherSelected(e,t){return t?.otherText===void 0?!1:e.multiple===!0||t.values.length===0}displayedRecordAnswer(e,t){if(t.answered)return{values:[...t.values],...t.otherText===void 0?{}:{otherText:t.otherText},fromDraft:!1};if(e.reason!==`superseded`)return;let n=Wl([t.question],this.answers).answers[0];if(n!==void 0)return{values:[...n.values],...n.otherText===void 0?{}:{otherText:n.otherText},fromDraft:!0}}optionLabel(e,t){return e.options.find(e=>e.value===t)?.label??t}currentModelIdentity(){if(this.outcome!==void 0)return`record:${this.draftSessionId}:${this.outcome.askId}`;if(this.ask!==void 0)return`open:${this.draftSessionId}:${this.ask.askId}`}loadCurrentDraft(){let e=this.outcome?.askId??this.ask?.askId;return e===void 0||this.draftSessionId===``?{}:Ll(this.draftSessionId,e)}questionGroupName(e,t){return`ask-user:${e.askId}:${t.id}`}questionFieldsetId(e){return`ask-user-question-${String(e)}`}questionDetailId(e){return`ask-user-question-detail-${String(e)}`}otherInputId(e){return`ask-user-other-${String(e)}`}recordQuestionHeadingId(e){return`ask-user-record-question-${String(e)}`}static{this.styles=h`
2535
+ `}changeOption(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;if(e.multiple!==!0){r.checked&&this.setAnswer(e,{values:[t]});return}let i=this.answers[e.id],a=r.checked?[...new Set([...i?.values??[],t])]:(i?.values??[]).filter(e=>e!==t);this.setAnswer(e,{values:a,...i?.otherText===void 0?{}:{otherText:i.otherText}})}changeOther(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;let i=this.answers[e.id];e.multiple===!0?this.setAnswer(e,{values:[...i?.values??[]],...r.checked?{otherText:i?.otherText??``}:{}}):r.checked&&this.setAnswer(e,{values:[],otherText:this.isOtherSelected(e,i)?i?.otherText??``:``}),r.checked&&this.focusOtherInput(t)}changeOtherText(e,t){let n=t.currentTarget;if(!(n instanceof HTMLTextAreaElement))return;iw(n);let r=this.answers[e.id];this.setAnswer(e,{values:[...r?.values??[]],otherText:n.value.slice(0,Pt)})}setAnswer(e,t){let n=t.values.length===0&&t.otherText===void 0?Object.fromEntries(Object.entries(this.answers).filter(([t])=>t!==e.id)):{...this.answers,[e.id]:t};this.answers=n,this.confirmingPartialSubmit=!1,this.ask!==void 0&&this.draftSessionId!==``&&Rl(this.draftSessionId,this.ask.askId,n)}handleSubmit(e,t){if(e.preventDefault(),!this.submitting){if(Ul(t.questions,this.answers).length>0){this.showPartialSubmitConfirmation();return}this.submitAnswers(t)}}submitAnswers(e){if(this.submitting)return;this.submitting=!0;let t=this.onSubmit;if(t===void 0){this.submitting=!1;return}let n=e.askId;Promise.resolve().then(()=>t(n,Wl(e.questions,this.answers))).catch(()=>{}).finally(()=>{this.ask?.askId===n&&(this.submitting=!1)})}async showPartialSubmitConfirmation(){this.confirmingPartialSubmit=!0,await this.updateComplete,this.renderRoot.querySelector(`.send-anyway`)?.focus()}keepEditing(e,t){this.confirmingPartialSubmit=!1;let n=t[0];n!==void 0&&this.focusQuestion(e.questions.indexOf(n))}focusQuestion(e){e<0||this.updateComplete.then(()=>{let t=this.renderRoot.querySelector(`#${this.questionFieldsetId(e)}`);(t?.querySelector(`input, textarea`)??t)?.focus()})}async focusOtherInput(e){await this.updateComplete,this.renderRoot.querySelector(`#${this.otherInputId(e)}`)?.focus()}isOtherSelected(e,t){return t?.otherText===void 0?!1:e.multiple===!0||t.values.length===0}displayedRecordAnswer(e,t){if(t.answered)return{values:[...t.values],...t.otherText===void 0?{}:{otherText:t.otherText},fromDraft:!1};if(e.reason!==`superseded`)return;let n=Wl([t.question],this.answers).answers[0];if(n!==void 0)return{values:[...n.values],...n.otherText===void 0?{}:{otherText:n.otherText},fromDraft:!0}}optionLabel(e,t){return e.options.find(e=>e.value===t)?.label??t}currentModelIdentity(){if(this.outcome!==void 0)return`record:${this.draftSessionId}:${this.outcome.askId}`;if(this.ask!==void 0)return`open:${this.draftSessionId}:${this.ask.askId}`}loadCurrentDraft(){let e=this.outcome?.askId??this.ask?.askId;return e===void 0||this.draftSessionId===``?{}:Ll(this.draftSessionId,e)}questionGroupName(e,t){return`ask-user:${e.askId}:${t.id}`}questionFieldsetId(e){return`ask-user-question-${String(e)}`}questionDetailId(e){return`ask-user-question-detail-${String(e)}`}otherInputId(e){return`ask-user-other-${String(e)}`}recordQuestionHeadingId(e){return`ask-user-record-question-${String(e)}`}static{this.styles=h`
2523
2536
  :host {
2524
2537
  display: block;
2525
2538
  box-sizing: border-box;
@@ -2704,9 +2717,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2704
2717
  .confirmation-actions { justify-content: flex-end; }
2705
2718
  .primary-action { min-height: 42px; }
2706
2719
  }
2707
- `}};H([b({attribute:!1})],iw.prototype,`ask`,void 0),H([b({attribute:!1})],iw.prototype,`outcome`,void 0),H([b({attribute:!1})],iw.prototype,`draftSessionId`,void 0),H([b({attribute:!1})],iw.prototype,`onSubmit`,void 0),H([x()],iw.prototype,`answers`,void 0),H([x()],iw.prototype,`step`,void 0),H([x()],iw.prototype,`confirmingPartialSubmit`,void 0),H([x()],iw.prototype,`submitting`,void 0),iw=H([y(`ask-user-card`)],iw);var aw=1e3,ow=120;function sw(e){let t=e.replace(/\r\n/g,`
2720
+ `}};H([b({attribute:!1})],aw.prototype,`ask`,void 0),H([b({attribute:!1})],aw.prototype,`outcome`,void 0),H([b({attribute:!1})],aw.prototype,`draftSessionId`,void 0),H([b({attribute:!1})],aw.prototype,`onSubmit`,void 0),H([x()],aw.prototype,`answers`,void 0),H([x()],aw.prototype,`step`,void 0),H([x()],aw.prototype,`confirmingPartialSubmit`,void 0),H([x()],aw.prototype,`submitting`,void 0),aw=H([y(`ask-user-card`)],aw);var ow=1e3,sw=120;function cw(e){let t=e.replace(/\r\n/g,`
2708
2721
  `).replace(/^\n+/,``).trimEnd(),n=t.indexOf(`
2709
- `);if(n===-1)return t.length<=ow?{heading:t}:{heading:`${t.slice(0,ow).trimEnd()}\u2026`,body:t};let r=t.slice(0,n).trimEnd(),i=r.length<=ow,a=i?r:`${r.slice(0,ow).trimEnd()}\u2026`,o=i?t.slice(n+1).replace(/\n+$/,``):t;return o.trim()===``?{heading:a}:{heading:a,body:o}}function cw(e){switch(e){case`answered`:return`Answered`;case`cancelled`:return`Cancelled`;case`timeout`:return`Timed out`;case`aborted`:return`Aborted`;case`session-ended`:return`Session ended`}}function lw(e){switch(e.reason){case`answered`:{let t=e.answer;return t===void 0?`Closed without an answer.`:typeof t==`boolean`?`Answered: ${t?`Yes`:`No`}`:t===``?`Answered with an empty response.`:`Answered: ${t}`}case`cancelled`:return`Dismissed without an answer.`;case`timeout`:return`No answer was given before the dialog timed out.`;case`aborted`:return`The run ended before this dialog was answered.`;case`session-ended`:return`The session ended before this dialog was answered.`}}function uw(e,t){if(e===void 0)return;let n=Date.parse(e);if(!Number.isFinite(n))return;let r=n-t;if(r<=0)return`Auto-cancel imminent`;let i=Math.ceil(r/1e3);if(i>=3600){let e=Math.floor(i/3600),t=Math.floor(i%3600/60);return`Auto-cancels in ${String(e)}h ${String(t)}m`}if(i>=60){let e=Math.floor(i/60);return`Auto-cancels in ${String(e)}m ${String(i%60)}s`}return`Auto-cancels in ${String(i)}s`}var dw=class extends v{constructor(...e){super(...e),this.inputValue=``,this.closing=!1,this.countdownNow=0}connectedCallback(){super.connectedCallback(),this.syncCountdownTimer()}disconnectedCallback(){this.stopCountdownTimer(),super.disconnectedCallback()}willUpdate(e){if(!e.has(`dialog`)&&!e.has(`outcome`))return;let t=this.currentIdentity();t!==this.dialogIdentity&&(this.dialogIdentity=t,this.inputValue=``,this.closing=!1),this.syncCountdownTimer()}render(){return this.outcome===void 0?this.dialog===void 0?null:this.renderOpen(this.dialog):this.renderClosed(this.outcome)}renderOpen(e){let t=uw(e.timeoutAt,this.countdownNow===0?Date.now():this.countdownNow),{heading:n,body:r}=sw(e.title);return g`
2722
+ `);if(n===-1)return t.length<=sw?{heading:t}:{heading:`${t.slice(0,sw).trimEnd()}\u2026`,body:t};let r=t.slice(0,n).trimEnd(),i=r.length<=sw,a=i?r:`${r.slice(0,sw).trimEnd()}\u2026`,o=i?t.slice(n+1).replace(/\n+$/,``):t;return o.trim()===``?{heading:a}:{heading:a,body:o}}function lw(e){switch(e){case`answered`:return`Answered`;case`cancelled`:return`Cancelled`;case`timeout`:return`Timed out`;case`aborted`:return`Aborted`;case`session-ended`:return`Session ended`}}function uw(e){switch(e.reason){case`answered`:{let t=e.answer;return t===void 0?`Closed without an answer.`:typeof t==`boolean`?`Answered: ${t?`Yes`:`No`}`:t===``?`Answered with an empty response.`:`Answered: ${t}`}case`cancelled`:return`Dismissed without an answer.`;case`timeout`:return`No answer was given before the dialog timed out.`;case`aborted`:return`The run ended before this dialog was answered.`;case`session-ended`:return`The session ended before this dialog was answered.`}}function dw(e,t){if(e===void 0)return;let n=Date.parse(e);if(!Number.isFinite(n))return;let r=n-t;if(r<=0)return`Auto-cancel imminent`;let i=Math.ceil(r/1e3);if(i>=3600){let e=Math.floor(i/3600),t=Math.floor(i%3600/60);return`Auto-cancels in ${String(e)}h ${String(t)}m`}if(i>=60){let e=Math.floor(i/60);return`Auto-cancels in ${String(e)}m ${String(i%60)}s`}return`Auto-cancels in ${String(i)}s`}var fw=class extends v{constructor(...e){super(...e),this.inputValue=``,this.closing=!1,this.countdownNow=0}connectedCallback(){super.connectedCallback(),this.syncCountdownTimer()}disconnectedCallback(){this.stopCountdownTimer(),super.disconnectedCallback()}willUpdate(e){if(!e.has(`dialog`)&&!e.has(`outcome`))return;let t=this.currentIdentity();t!==this.dialogIdentity&&(this.dialogIdentity=t,this.inputValue=``,this.closing=!1),this.syncCountdownTimer()}render(){return this.outcome===void 0?this.dialog===void 0?null:this.renderOpen(this.dialog):this.renderClosed(this.outcome)}renderOpen(e){let t=dw(e.timeoutAt,this.countdownNow===0?Date.now():this.countdownNow),{heading:n,body:r}=cw(e.title);return g`
2710
2723
  <article class="card open-card" aria-labelledby="extension-dialog-heading">
2711
2724
  <header class="card-header">
2712
2725
  <h2 id="extension-dialog-heading">${n}</h2>
@@ -2752,15 +2765,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2752
2765
  `}renderClosed(e){return g`
2753
2766
  <article class="card closed-card" aria-labelledby="extension-dialog-closed-heading">
2754
2767
  <header class="card-header">
2755
- <h2 id="extension-dialog-closed-heading">${sw(e.dialog.title).heading}</h2>
2756
- <span class=${`header-status ${e.reason}`}>${cw(e.reason)}</span>
2768
+ <h2 id="extension-dialog-closed-heading">${cw(e.dialog.title).heading}</h2>
2769
+ <span class=${`header-status ${e.reason}`}>${lw(e.reason)}</span>
2757
2770
  </header>
2758
- <p class="closed-summary">${lw(e)}</p>
2771
+ <p class="closed-summary">${uw(e)}</p>
2759
2772
  <footer class="dialog-footer">
2760
2773
  <button class="secondary-action" type="button" @click=${()=>{this.dismissClosed(e)}}>Dismiss</button>
2761
2774
  </footer>
2762
2775
  </article>
2763
- `}answerDialog(e,t){this.closeWith(e,()=>this.onAnswer?.(e.dialogId,t))}cancelDialog(e){this.closeWith(e,()=>this.onCancel?.(e.dialogId))}submitInput(e,t){e.preventDefault(),this.answerDialog(t,this.inputValue)}closeWith(e,t){if(this.closing)return;this.closing=!0;let n=e.dialogId;Promise.resolve().then(t).catch(()=>{}).finally(()=>{this.dialog?.dialogId===n&&(this.closing=!1)})}changeInput(e){let t=e.currentTarget;t instanceof HTMLInputElement&&(this.inputValue=t.value)}dismissClosed(e){this.onDismiss?.(e.dialog.dialogId)}currentIdentity(){if(this.outcome!==void 0)return`closed:${this.outcome.dialog.dialogId}`;if(this.dialog!==void 0)return`open:${this.dialog.dialogId}`}syncCountdownTimer(){let e=this.isConnected&&this.outcome===void 0&&this.dialog?.timeoutAt!==void 0;if(e&&this.countdownTimer===void 0){this.countdownNow=Date.now(),this.countdownTimer=window.setInterval(()=>{this.countdownNow=Date.now()},aw);return}e||this.stopCountdownTimer()}stopCountdownTimer(){this.countdownTimer!==void 0&&(window.clearInterval(this.countdownTimer),this.countdownTimer=void 0)}static{this.styles=h`
2776
+ `}answerDialog(e,t){this.closeWith(e,()=>this.onAnswer?.(e.dialogId,t))}cancelDialog(e){this.closeWith(e,()=>this.onCancel?.(e.dialogId))}submitInput(e,t){e.preventDefault(),this.answerDialog(t,this.inputValue)}closeWith(e,t){if(this.closing)return;this.closing=!0;let n=e.dialogId;Promise.resolve().then(t).catch(()=>{}).finally(()=>{this.dialog?.dialogId===n&&(this.closing=!1)})}changeInput(e){let t=e.currentTarget;t instanceof HTMLInputElement&&(this.inputValue=t.value)}dismissClosed(e){this.onDismiss?.(e.dialog.dialogId)}currentIdentity(){if(this.outcome!==void 0)return`closed:${this.outcome.dialog.dialogId}`;if(this.dialog!==void 0)return`open:${this.dialog.dialogId}`}syncCountdownTimer(){let e=this.isConnected&&this.outcome===void 0&&this.dialog?.timeoutAt!==void 0;if(e&&this.countdownTimer===void 0){this.countdownNow=Date.now(),this.countdownTimer=window.setInterval(()=>{this.countdownNow=Date.now()},ow);return}e||this.stopCountdownTimer()}stopCountdownTimer(){this.countdownTimer!==void 0&&(window.clearInterval(this.countdownTimer),this.countdownTimer=void 0)}static{this.styles=h`
2764
2777
  :host {
2765
2778
  display: block;
2766
2779
  box-sizing: border-box;
@@ -2896,7 +2909,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2896
2909
  .primary-action, .secondary-action, .option-button { min-height: 42px; }
2897
2910
  .dialog-detail { max-height: min(40vh, 320px); }
2898
2911
  }
2899
- `}};H([b({attribute:!1})],dw.prototype,`dialog`,void 0),H([b({attribute:!1})],dw.prototype,`outcome`,void 0),H([b({attribute:!1})],dw.prototype,`onAnswer`,void 0),H([b({attribute:!1})],dw.prototype,`onCancel`,void 0),H([b({attribute:!1})],dw.prototype,`onDismiss`,void 0),H([x()],dw.prototype,`inputValue`,void 0),H([x()],dw.prototype,`closing`,void 0),H([x()],dw.prototype,`countdownNow`,void 0),dw=H([y(`extension-dialog-card`)],dw);var fw=class extends v{constructor(...e){super(...e),this.positionPercent=0,this.loadedPercent=100}render(){let e=pw(this.positionPercent),t=pw(this.loadedPercent),n=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return g`
2912
+ `}};H([b({attribute:!1})],fw.prototype,`dialog`,void 0),H([b({attribute:!1})],fw.prototype,`outcome`,void 0),H([b({attribute:!1})],fw.prototype,`onAnswer`,void 0),H([b({attribute:!1})],fw.prototype,`onCancel`,void 0),H([b({attribute:!1})],fw.prototype,`onDismiss`,void 0),H([x()],fw.prototype,`inputValue`,void 0),H([x()],fw.prototype,`closing`,void 0),H([x()],fw.prototype,`countdownNow`,void 0),fw=H([y(`extension-dialog-card`)],fw);var pw=class extends v{constructor(...e){super(...e),this.positionPercent=0,this.loadedPercent=100}render(){let e=mw(this.positionPercent),t=mw(this.loadedPercent),n=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return g`
2900
2913
  <div
2901
2914
  class="meter"
2902
2915
  style=${`--position:${e.toFixed(2)}%;`}
@@ -2919,18 +2932,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2919
2932
  .track { position: relative; height: 4px; margin-top: 4px; border-radius: 999px; background: color-mix(in srgb, var(--pi-border-muted) 34%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--pi-bg) 55%, transparent); }
2920
2933
  .progress { position: absolute; left: 0; width: var(--position); top: 0; bottom: 0; border-radius: 999px; background: color-mix(in srgb, var(--pi-accent) 42%, var(--pi-border-muted)); }
2921
2934
  .marker { position: absolute; left: var(--position); top: 50%; width: 10px; height: 10px; border: 2px solid var(--pi-bg); border-radius: 50%; background: var(--pi-accent); box-shadow: 0 2px 8px var(--pi-shadow); transform: translate(-50%, -50%); }
2922
- `}};H([b({type:Number})],fw.prototype,`positionPercent`,void 0),H([b({type:Number})],fw.prototype,`loadedPercent`,void 0),fw=H([y(`conversation-meter`)],fw);function pw(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}var mw=new B.Renderer;mw.html=({text:e})=>vw(e);var hw=300,gw=new Map;function _w(e){let t=gw.get(e);if(t!==void 0)return t;let n=bw(B.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:mw}));if(gw.set(e,n),gw.size>hw){let e=gw.keys().next().value;e!==void 0&&gw.delete(e)}return n}function vw(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}var yw=`table-scroll`;function bw(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`)&&!Sw(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),xw(t.content),t.innerHTML}function xw(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(yw)===!0)return;let t=document.createElement(`div`);t.className=yw,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,`Table`),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function Sw(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var Cw=class extends v{constructor(...e){super(...e),this.text=``,this.parsedText=``,this.parsedHtml=``,this.enhancedForHtml=``,this.streamingSuffix=``,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(){if(!(this.parsedText.length>0&&this.text.startsWith(this.parsedText)&&this.text.length>this.parsedText.length))return this.text!==this.parsedText&&(this.parsedHtml=_w(this.text),this.parsedText=this.text),this.settleTimer=void 0,this.streamingSuffix=``,g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${hg(this.parsedHtml)}</div>`;let e=this.text.slice(this.parsedText.length);return this.streamingSuffix=e,this.scheduleSettleParse(),g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${hg(this.parsedHtml)}${e===``?``:g`<span class="stream-suffix">${e}</span>`}</div>`}updated(){this.enhancedForHtml!==this.parsedHtml&&(this.enhancedForHtml=this.parsedHtml,this.enhanceCodeBlocks())}scheduleSettleParse(){this.settleTimer===void 0&&(this.settleTimer=setTimeout(()=>{this.settleTimer=void 0,this.parsedText!==this.text&&(this.parsedHtml=_w(this.text),this.parsedText=this.text,this.streamingSuffix=``,this.requestUpdate())},350))}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 Ex(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=og}};H([b()],Cw.prototype,`text`,void 0),Cw=H([y(`formatted-text`)],Cw);var ww=180,Tw=class extends v{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=Dw(e.args),n=kw(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:Aw(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=Ew(e,t);return g`
2935
+ `}};H([b({type:Number})],pw.prototype,`positionPercent`,void 0),H([b({type:Number})],pw.prototype,`loadedPercent`,void 0),pw=H([y(`conversation-meter`)],pw);function mw(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}var hw=new B.Renderer;hw.html=({text:e})=>yw(e);var gw=300,_w=new Map;function vw(e){let t=_w.get(e);if(t!==void 0)return t;let n=xw(B.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:hw}));if(_w.set(e,n),_w.size>gw){let e=_w.keys().next().value;e!==void 0&&_w.delete(e)}return n}function yw(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}var bw=`table-scroll`;function xw(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`)&&!Cw(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),Sw(t.content),t.innerHTML}function Sw(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(bw)===!0)return;let t=document.createElement(`div`);t.className=bw,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,`Table`),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function Cw(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var ww=class extends v{constructor(...e){super(...e),this.text=``,this.parsedText=``,this.parsedHtml=``,this.enhancedForHtml=``,this.streamingSuffix=``,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(){if(!(this.parsedText.length>0&&this.text.startsWith(this.parsedText)&&this.text.length>this.parsedText.length))return this.text!==this.parsedText&&(this.parsedHtml=vw(this.text),this.parsedText=this.text),this.settleTimer=void 0,this.streamingSuffix=``,g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${hg(this.parsedHtml)}</div>`;let e=this.text.slice(this.parsedText.length);return this.streamingSuffix=e,this.scheduleSettleParse(),g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${hg(this.parsedHtml)}${e===``?``:g`<span class="stream-suffix">${e}</span>`}</div>`}updated(){this.enhancedForHtml!==this.parsedHtml&&(this.enhancedForHtml=this.parsedHtml,this.enhanceCodeBlocks())}scheduleSettleParse(){this.settleTimer===void 0&&(this.settleTimer=setTimeout(()=>{this.settleTimer=void 0,this.parsedText!==this.text&&(this.parsedHtml=vw(this.text),this.parsedText=this.text,this.streamingSuffix=``,this.requestUpdate())},350))}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 Ex(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=og}};H([b()],ww.prototype,`text`,void 0),ww=H([y(`formatted-text`)],ww);var Tw=180,Ew=class extends v{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=Ow(e.args),n=Aw(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:jw(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=Dw(e,t);return g`
2923
2936
  <section class=${`tool-card ${e.status}`}>
2924
2937
  <div class="tool-header">
2925
2938
  <div class="tool-title">
2926
- <span class="status-icon" aria-hidden="true">${Pw(e.status)}</span>
2939
+ <span class="status-icon" aria-hidden="true">${Fw(e.status)}</span>
2927
2940
  <strong>${e.toolName}</strong>
2928
2941
  ${this.renderHeaderTarget(l)}
2929
2942
  </div>
2930
2943
  <div class="tool-meta">
2931
- ${Ow(e)===void 0?null:g`<span>${Ow(e)}</span>`}
2944
+ ${kw(e)===void 0?null:g`<span>${kw(e)}</span>`}
2932
2945
  ${a===void 0?null:g`<span class="diff-stats"><b class="added">+${a.added}</b><span>/</span><b class="removed">-${a.removed}</b></span>`}
2933
- <span class="status-label">${Fw(e.status)}</span>
2946
+ <span class="status-label">${Iw(e.status)}</span>
2934
2947
  </div>
2935
2948
  </div>
2936
2949
 
@@ -2955,7 +2968,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2955
2968
  `}
2956
2969
  </details>
2957
2970
  `}renderDiffBody(e,t,n){let r=e.split(`
2958
- `),i=!this.showFullDiff&&r.length>ww,a=i?r.slice(0,ww):r;return g`
2971
+ `),i=!this.showFullDiff&&r.length>Tw,a=i?r.slice(0,Tw):r;return g`
2959
2972
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
2960
2973
  <summary>
2961
2974
  <span>${t}</span>
@@ -2966,7 +2979,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2966
2979
  <span>${i?`Showing ${String(a.length)} of ${String(r.length)} lines`:`Full diff`}</span>
2967
2980
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?`Copied`:`Copy diff`}</button>
2968
2981
  </div>
2969
- <pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${jw(e)}>${e}</span>`)}</code></pre>
2982
+ <pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${Mw(e)}>${e}</span>`)}</code></pre>
2970
2983
  ${i?g`
2971
2984
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
2972
2985
  Show all ${String(r.length)} diff lines
@@ -3017,34 +3030,43 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3017
3030
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
3018
3031
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
3019
3032
  .show-more { justify-self: start; }
3020
- `}};H([b({attribute:!1})],Tw.prototype,`execution`,void 0),H([x()],Tw.prototype,`showFullDiff`,void 0),H([x()],Tw.prototype,`copied`,void 0),H([x()],Tw.prototype,`diffOpen`,void 0),Tw=H([y(`tool-execution-view`)],Tw);function Ew(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=Rw(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function Dw(e){return Rw(e,`path`)??Rw(e,`file_path`)}function Ow(e){if(e.toolName!==`edit`)return;let t=Lw(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof Lw(e.args,`oldText`)==`string`&&typeof Lw(e.args,`newText`)==`string`)return`1 edit`}function kw(e){return Rw(e,`diff`)}function Aw(e){let t=0,n=0;for(let r of e.split(`
3021
- `))Mw(r)?t++:Nw(r)&&n++;return{added:t,removed:n}}function jw(e){return Mw(e)?`added`:Nw(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function Mw(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function Nw(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function Pw(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function Fw(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function Iw(e){return typeof e==`object`&&!!e}function Lw(e,t){return Iw(e)?e[t]:void 0}function Rw(e,t){let n=Lw(e,t);return typeof n==`string`?n:void 0}var zw=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),Bw=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function Vw(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`queuedMessages`);if(Array.isArray(t))return{queuedMessages:t}}function Hw(e){return g`
3033
+ `}};H([b({attribute:!1})],Ew.prototype,`execution`,void 0),H([x()],Ew.prototype,`showFullDiff`,void 0),H([x()],Ew.prototype,`copied`,void 0),H([x()],Ew.prototype,`diffOpen`,void 0),Ew=H([y(`tool-execution-view`)],Ew);function Dw(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=zw(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function Ow(e){return zw(e,`path`)??zw(e,`file_path`)}function kw(e){if(e.toolName!==`edit`)return;let t=Rw(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof Rw(e.args,`oldText`)==`string`&&typeof Rw(e.args,`newText`)==`string`)return`1 edit`}function Aw(e){return zw(e,`diff`)}function jw(e){let t=0,n=0;for(let r of e.split(`
3034
+ `))Nw(r)?t++:Pw(r)&&n++;return{added:t,removed:n}}function Mw(e){return Nw(e)?`added`:Pw(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function Nw(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function Pw(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function Fw(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function Iw(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function Lw(e){return typeof e==`object`&&!!e}function Rw(e,t){return Lw(e)?e[t]:void 0}function zw(e,t){let n=Rw(e,t);return typeof n==`string`?n:void 0}var Bw=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),Vw=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function Hw(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`queuedMessages`);if(Array.isArray(t))return{queuedMessages:t}}function Uw(e){return g`
3022
3035
  <svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3023
3036
  <path d="m9 18 6-6-6-6"></path>
3024
3037
  </svg>
3025
- `}function Uw(){return g`
3038
+ `}function Ww(){return g`
3026
3039
  <svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3027
3040
  <path d="M6 6l12 12"></path>
3028
3041
  <path d="M18 6 6 18"></path>
3029
3042
  </svg>
3030
- `}function Ww(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 Gw(e){return Kw(e,0,100)}function Kw(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function qw(e){if(e.state===`sending`)return{glyph:`◌`,text:`Sending`,label:`Sending`,tone:`pending`};if(e.state===`failed`)return{glyph:`!`,text:`Not sent`,label:`Not sent - the server never received this message`,tone:`failed`};if(e.state===`queued`){let t=e.kind===`steer`?`Queued to steer`:`Queued`;return{glyph:`✓`,text:t,label:`${t} - the server has this message and the agent will take it next`,tone:`received`}}return e.state===`received`?{glyph:`✓`,text:`Sent`,label:`Sent - the server received this message`,tone:`received`}:{glyph:`✓✓`,text:`Read`,label:`Read - the agent took this message into the conversation`,tone:`delivered`}}function Jw(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function Yw(e){return e===void 0||e===``?`tool output`:`${e} output`}function Xw(e){return`m:${String(e)}`}function Zw(e){return`g:${String(e)}`}function Qw(e){return`e:${String(e)}`}function $w(e){return`g:${String(e)}`}function eT(e){return e?`msg event-group live`:`msg event-group`}function tT(e){return e?`live events`:`events`}function nT(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 rT(e){let t=e.meta?.timestamp;return[t===void 0?void 0:iT(t),aT(e),e.meta?.thinkingLevel].filter(e=>e!==void 0&&e!==``).join(` · `)}function iT(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return zw.format(t)}function aT(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var K=class extends v{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.askDraftSessionId=``,this.pendingDialogs=[],this.closedDialogs=[],this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedTopDrawerKeys=new Set,this.expandedTopDrawerKeys=new Set,this.goals=[],this.activityFilter=`all`,this.activityScope=`active`,this.turnNowMs=0,this.disclosures=new XS,this.scrollController=new TC,this.drawerTabEdgeTracker=new VC(()=>{this.requestUpdate()}),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.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.status?.queuedMessages??[])},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},this.closeActivityOutput=()=>{this.activityOutput!==void 0&&this.onCloseActivityOutput?.()},this.onActivityOutputDialogClick=e=>{e.target===this.activityOutputDialog&&this.closeActivityOutput()}}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),window.addEventListener(`pagehide`,this.onPageHide),window.visualViewport?.addEventListener(`resize`,this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.stopTurnClock(),this.saveScrollPosition(),this.scrollController.dispose(),this.drawerTabEdgeTracker.dispose(),this.releaseImageZoomModal(),this.releaseActivityOutputModal(),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.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=void 0),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener(`resize`,this.onViewportResize),window.removeEventListener(`pagehide`,this.onPageHide),window.visualViewport?.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!=`string`||e===``||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.turnStartedAtMs=void 0,this.disclosures.syncSession(this.sessionId),this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0),this.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=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`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&(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();let t=e.has(`pendingAsk`)&&this.isNewPendingAsk(e.get(`pendingAsk`)),n=e.has(`pendingDialogs`)&&this.isNewOpenDialog(e.get(`pendingDialogs`));!e.has(`sessionId`)&&t&&this.pinnedToBottom?this.scrollToOpenAsk():!e.has(`sessionId`)&&n&&this.pinnedToBottom?this.scrollToOpenDialog():!e.has(`sessionId`)&&(e.has(`messages`)||this.queueGrew(e.get(`status`))||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&this.pinnedToBottom&&this.scrollToBottom(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`messageTotal`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.scheduleConversationRailUpdate(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`hasMore`)||e.has(`loadingMore`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&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(),e.has(`activityOutput`)&&this.syncActivityOutputDialog(),this.drawerTabEdgeTracker.observe(this.drawerTabs??void 0),(e.has(`status`)||e.has(`activity`)||e.has(`isSendingPrompt`))&&this.syncTurnClock()}syncImageZoomDialog(){let e=this.imageZoomDialog;if(e!==void 0){if(this.zoomedImage!==void 0){if(this.imageZoomModalRegistration===void 0){let t=Rh({element:e,nativeTopLayer:!0,focus:()=>{(this.renderRoot.querySelector(`.image-zoom-close`)??e).focus()}});this.imageZoomModalRegistration=t;try{e.open||e.showModal()}catch(e){throw this.imageZoomModalRegistration=void 0,t.unregister(),e}}this.imageZoomModalRegistration.focus();return}e.open&&e.close(),this.releaseImageZoomModal()}}syncActivityOutputDialog(){let e=this.activityOutputDialog;if(e!==void 0){if(this.activityOutput!==void 0){if(this.activityOutputModalRegistration===void 0){let t=Rh({element:e,nativeTopLayer:!0,focus:()=>{(this.renderRoot.querySelector(`.activity-output-close`)??e).focus()}});this.activityOutputModalRegistration=t;try{e.open||e.showModal()}catch(e){throw this.activityOutputModalRegistration=void 0,t.unregister(),e}}this.activityOutputModalRegistration.focus();return}e.open&&e.close(),this.releaseActivityOutputModal()}}releaseActivityOutputModal(){let e=this.activityOutputModalRegistration;this.activityOutputModalRegistration=void 0,e?.unregister()}releaseImageZoomModal(){let e=this.imageZoomModalRegistration;this.imageZoomModalRegistration=void 0,e?.unregister()}notificationTargetChanged(e){let t=this.notificationInbox;return!Ww(e)||t===void 0?e!==t:ep(e)!==ep(t)}render(){let e=this.groupedMessages();return g`
3043
+ `}function Gw(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 Kw(e){return qw(e,0,100)}function qw(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function Jw(e){if(e.state===`sending`)return{glyph:`◌`,text:`Sending`,label:`Sending`,tone:`pending`};if(e.state===`failed`)return{glyph:`!`,text:`Not sent`,label:`Not sent - the server never received this message`,tone:`failed`};if(e.state===`queued`){let t=e.kind===`steer`?`Queued to steer`:`Queued`;return{glyph:`✓`,text:t,label:`${t} - the server has this message and the agent will take it next`,tone:`received`}}return e.state===`received`?{glyph:`✓`,text:`Sent`,label:`Sent - the server received this message`,tone:`received`}:{glyph:`✓✓`,text:`Read`,label:`Read - the agent took this message into the conversation`,tone:`delivered`}}function Yw(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function Xw(e){return e===void 0||e===``?`tool output`:`${e} output`}function Zw(e){return`m:${String(e)}`}function Qw(e){return`g:${String(e)}`}function $w(e){return`e:${String(e)}`}function eT(e){return`g:${String(e)}`}function tT(e){return e?`msg event-group live`:`msg event-group`}function nT(e){return e?`live events`:`events`}function rT(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 iT(e){let t=e.meta?.timestamp;return[t===void 0?void 0:aT(t),oT(e),e.meta?.thinkingLevel].filter(e=>e!==void 0&&e!==``).join(` · `)}function aT(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return Bw.format(t)}function oT(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var K=class extends v{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.askDraftSessionId=``,this.pendingDialogs=[],this.closedDialogs=[],this.warningsVisible=!0,this.pinnedToBottom=!0,this.jumpToBottomVisible=!1,this.zoomedImage=void 0,this.collapsedTopDrawerKeys=new Set,this.expandedTopDrawerKeys=new Set,this.goals=[],this.activityFilter=`all`,this.activityScope=`active`,this.turnNowMs=0,this.disclosures=new mC,this.scrollController=new US,this.drawerTabEdgeTracker=new HC(()=>{this.requestUpdate()}),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.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.status?.queuedMessages??[])},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},this.closeActivityOutput=()=>{this.activityOutput!==void 0&&this.onCloseActivityOutput?.()},this.onActivityOutputDialogClick=e=>{e.target===this.activityOutputDialog&&this.closeActivityOutput()}}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),window.addEventListener(`pagehide`,this.onPageHide),window.visualViewport?.addEventListener(`resize`,this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.stopTurnClock(),this.saveScrollPosition(),this.scrollController.dispose(),this.drawerTabEdgeTracker.dispose(),this.releaseImageZoomModal(),this.releaseActivityOutputModal(),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.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=void 0),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener(`resize`,this.onViewportResize),window.removeEventListener(`pagehide`,this.onPageHide),window.visualViewport?.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!=`string`||e===``||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.turnStartedAtMs=void 0,this.disclosures.syncSession(this.sessionId),this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0),this.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=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`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&(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();let t=e.has(`pendingAsk`)&&this.isNewPendingAsk(e.get(`pendingAsk`)),n=e.has(`pendingDialogs`)&&this.isNewOpenDialog(e.get(`pendingDialogs`));!e.has(`sessionId`)&&t&&this.pinnedToBottom?this.scrollToOpenAsk():!e.has(`sessionId`)&&n&&this.pinnedToBottom?this.scrollToOpenDialog():!e.has(`sessionId`)&&(e.has(`messages`)||this.queueGrew(e.get(`status`))||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&this.pinnedToBottom&&this.scrollToBottom(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`messageTotal`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.scheduleConversationRailUpdate(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`hasMore`)||e.has(`loadingMore`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&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(),e.has(`activityOutput`)&&this.syncActivityOutputDialog(),this.drawerTabEdgeTracker.observe(this.drawerTabs??void 0),(e.has(`status`)||e.has(`activity`)||e.has(`isSendingPrompt`))&&this.syncTurnClock()}syncImageZoomDialog(){let e=this.imageZoomDialog;if(e!==void 0){if(this.zoomedImage!==void 0){if(this.imageZoomModalRegistration===void 0){let t=Rh({element:e,nativeTopLayer:!0,focus:()=>{(this.renderRoot.querySelector(`.image-zoom-close`)??e).focus()}});this.imageZoomModalRegistration=t;try{e.open||e.showModal()}catch(e){throw this.imageZoomModalRegistration=void 0,t.unregister(),e}}this.imageZoomModalRegistration.focus();return}e.open&&e.close(),this.releaseImageZoomModal()}}syncActivityOutputDialog(){let e=this.activityOutputDialog;if(e!==void 0){if(this.activityOutput!==void 0){if(this.activityOutputModalRegistration===void 0){let t=Rh({element:e,nativeTopLayer:!0,focus:()=>{(this.renderRoot.querySelector(`.activity-output-close`)??e).focus()}});this.activityOutputModalRegistration=t;try{e.open||e.showModal()}catch(e){throw this.activityOutputModalRegistration=void 0,t.unregister(),e}}this.activityOutputModalRegistration.focus();return}e.open&&e.close(),this.releaseActivityOutputModal()}}releaseActivityOutputModal(){let e=this.activityOutputModalRegistration;this.activityOutputModalRegistration=void 0,e?.unregister()}releaseImageZoomModal(){let e=this.imageZoomModalRegistration;this.imageZoomModalRegistration=void 0,e?.unregister()}notificationTargetChanged(e){let t=this.notificationInbox;return!Gw(e)||t===void 0?e!==t:ep(e)!==ep(t)}render(){let e=this.groupedMessages();return g`
3031
3044
  ${this.renderTopNotices()}
3032
3045
  ${this.renderNotificationLiveRegions()}
3033
3046
  <div class="chat-wrap">
3034
3047
  ${this.renderConversationRail()}
3035
3048
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${e=>{this.onWheel(e)}} @touchstart=${e=>{this.onTouchStart(e)}} @touchmove=${e=>{this.onTouchMove(e)}}>
3036
3049
  ${this.renderHistoryBoundary()}
3037
- ${qS(e,e=>e.kind===`group`?this.groupRenderKey(e.startIndex):this.messageAnchorKey(e.index),(t,n)=>t.kind===`group`?this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,n)):t.kind===`tool-image`?this.renderToolImageOutput(t.message,t.index,t.toolName):this.renderMessage(t.message,t.index))}
3050
+ ${dC(e,e=>e.kind===`group`?this.groupRenderKey(e.startIndex):this.messageAnchorKey(e.index),(t,n)=>t.kind===`group`?this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,n)):t.kind===`tool-image`?this.renderToolImageOutput(t.message,t.index,t.toolName):this.renderMessage(t.message,t.index))}
3038
3051
  ${this.renderSessionActivity()}
3039
3052
  ${this.renderQueuedMessages()}
3040
3053
  ${this.renderOpenAsk()}
3041
3054
  ${this.renderExtensionDialogs()}
3042
3055
  </div>
3056
+ ${this.renderJumpToBottom()}
3043
3057
  ${this.renderActivityDock()}
3044
3058
  </div>
3045
3059
  ${this.renderImageZoom()}
3046
3060
  ${this.renderActivityOutput()}
3047
- `}renderTopNotices(){let e=this.renderWarnings(),t=this.renderTopDrawer();return e===null&&t===null?null:g`<div class="top-notices">${e}${t}</div>`}renderTopDrawer(){let e=this.activityPanelState(),t=this.visibleNotificationInbox();if(e===void 0&&t===void 0&&this.goals.length===0)return null;let n=bT({activity:e!==void 0,notifications:t!==void 0,goals:this.goals.length>0},this.topDrawerTab),r=this.topDrawerKey(),i=this.expandedTopDrawerKeys.has(r)?!1:this.collapsedTopDrawerKeys.has(r)||!yT(),a=i?`Show session activity and notifications`:`Hide session activity and notifications`,o=t===void 0?0:Xf(t);return g`
3061
+ `}renderJumpToBottom(){return this.jumpToBottomVisible?g`
3062
+ <button
3063
+ class="jump-to-bottom"
3064
+ type="button"
3065
+ title="Jump to the newest message"
3066
+ aria-label="Jump to the newest message"
3067
+ @click=${()=>{this.pinnedToBottom=!0,this.scrollToBottom(),this.jumpToBottomVisible=!1}}
3068
+ >↓</button>
3069
+ `:null}renderTopNotices(){let e=this.renderWarnings(),t=this.renderTopDrawer();return e===null&&t===null?null:g`<div class="top-notices">${e}${t}</div>`}renderTopDrawer(){let e=this.activityPanelState(),t=this.visibleNotificationInbox();if(e===void 0&&t===void 0&&this.goals.length===0)return null;let n=xT({activity:e!==void 0,notifications:t!==void 0,goals:this.goals.length>0},this.topDrawerTab),r=this.topDrawerKey(),i=this.expandedTopDrawerKeys.has(r)?!1:this.collapsedTopDrawerKeys.has(r)||!bT(),a=i?`Show session activity and notifications`:`Hide session activity and notifications`,o=t===void 0?0:Xf(t);return g`
3048
3070
  <section
3049
3071
  class=${`top-drawer${i?` collapsed`:``}`}
3050
3072
  role="region"
@@ -3052,7 +3074,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3052
3074
  @focusout=${e=>{this.releaseEmptyNotificationTray(e)}}
3053
3075
  >
3054
3076
  <header class="drawer-header" data-notification-focus="header" tabindex="-1">
3055
- <div class=${`drawer-tabs-frame${zC(this.drawerTabEdgeTracker.edges)}`}>
3077
+ <div class=${`drawer-tabs-frame${BC(this.drawerTabEdgeTracker.edges)}`}>
3056
3078
  <div class="drawer-tabs" role="tablist" aria-label="Session drawer sections" @scroll=${()=>{this.drawerTabEdgeTracker.refresh()}} @keydown=${e=>{this.onDrawerTabsKeydown(e)}}>
3057
3079
  ${e===void 0?null:g`
3058
3080
  <button
@@ -3066,7 +3088,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3066
3088
  @click=${()=>{this.selectTopDrawerTab(`activity`,i)}}
3067
3089
  >
3068
3090
  ${e.summary.working?g`<span class="subagent-dot working" aria-hidden="true"></span>`:null}
3069
- <span class="drawer-tab-label">${mT({active:e.activeCount,total:e.total})}</span>
3091
+ <span class="drawer-tab-label">${hT({active:e.activeCount,total:e.total})}</span>
3070
3092
  </button>
3071
3093
  `}
3072
3094
  ${t===void 0?null:g`
@@ -3119,7 +3141,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3119
3141
  aria-expanded=${String(!i)}
3120
3142
  aria-controls=${n===`activity`?`session-activity-list`:`session-notification-list`}
3121
3143
  @click=${()=>{this.toggleTopDrawer(i)}}
3122
- >${Hw(i)}</button>
3144
+ >${Uw(i)}</button>
3123
3145
  </div>
3124
3146
  </header>
3125
3147
  <div class="drawer-body" ?hidden=${i}>
@@ -3136,7 +3158,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3136
3158
  `:null}
3137
3159
  </div>
3138
3160
  </section>
3139
- `}visibleNotificationInbox(){let e=this.notificationInbox;if(e?.sessionId!==this.sessionId)return;let t=e.pendingDismissedIds.size>0||e.dismissAllPending,n=this.retainedEmptyNotificationTrayTargetKey===ep(e);if(!(Xf(e)===0&&!t&&!n))return e}topDrawerKey(){let e=this.notificationInbox;return e?.sessionId===this.sessionId?ep(e):JSON.stringify([null,null,this.sessionId])}toggleTopDrawer(e){let t=this.topDrawerKey(),n=new Set(this.collapsedTopDrawerKeys),r=new Set(this.expandedTopDrawerKeys);e?(n.delete(t),r.add(t)):(r.delete(t),n.add(t)),this.collapsedTopDrawerKeys=n,this.expandedTopDrawerKeys=r}selectTopDrawerTab(e,t){this.topDrawerTab=e,t&&this.toggleTopDrawer(t)}renderActivityFilters(e,t){let n=hT(e);return n.length<=1?null:g`
3161
+ `}visibleNotificationInbox(){let e=this.notificationInbox;if(e?.sessionId!==this.sessionId)return;let t=e.pendingDismissedIds.size>0||e.dismissAllPending,n=this.retainedEmptyNotificationTrayTargetKey===ep(e);if(!(Xf(e)===0&&!t&&!n))return e}topDrawerKey(){let e=this.notificationInbox;return e?.sessionId===this.sessionId?ep(e):JSON.stringify([null,null,this.sessionId])}toggleTopDrawer(e){let t=this.topDrawerKey(),n=new Set(this.collapsedTopDrawerKeys),r=new Set(this.expandedTopDrawerKeys);e?(n.delete(t),r.add(t)):(r.delete(t),n.add(t)),this.collapsedTopDrawerKeys=n,this.expandedTopDrawerKeys=r}selectTopDrawerTab(e,t){this.topDrawerTab=e,t&&this.toggleTopDrawer(t)}renderActivityFilters(e,t){let n=gT(e);return n.length<=1?null:g`
3140
3162
  <div class="activity-filters" role="group" aria-label="Filter session activity">
3141
3163
  ${n.map(e=>g`
3142
3164
  <button
@@ -3147,9 +3169,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3147
3169
  >${e.label} <span class="activity-filter-count">${String(e.count)}</span></button>
3148
3170
  `)}
3149
3171
  </div>
3150
- `}activityPanelState(){let e=this.subagents??[],t=this.subagentRuns??[],n=this.backgroundTasks??[];if(e.length===0&&t.length===0&&n.length===0)return;let r=CT(e),i=sT(t),a=cT(n),o=xT([...r.map(e=>e.status),...i.map(e=>e.status),...a.map(e=>e.status)]),s=[...r,...i,...a].filter(e=>fT(e.status)).length;return{rows:r,runRows:i,taskRows:a,summary:o,total:r.length+i.length+a.length,activeCount:s}}renderActivityPanel(e){let t=gT(this.activityFilter,e),n=e.activeCount===0&&this.activityScope===`active`?`empty-active`:this.activityScope,r=lT([...e.rows.map((e,t)=>({kind:`subagents`,index:t,status:e.status,row:e})),...e.runRows.map((e,t)=>({kind:`runs`,index:t,status:e.status,startedAt:e.run.startedAt,row:e})),...e.taskRows.map((e,t)=>({kind:`tasks`,index:t,status:e.status,startedAt:e.task.startedAt,row:e}))]).filter(e=>t===`all`||t===e.kind),i=r.filter(e=>n===`all`||!pT(e.status)),a=r.filter(e=>pT(e.status)).length;return g`
3172
+ `}activityPanelState(){let e=this.subagents??[],t=this.subagentRuns??[],n=this.backgroundTasks??[];if(e.length===0&&t.length===0&&n.length===0)return;let r=wT(e),i=cT(t),a=lT(n),o=ST([...r.map(e=>e.status),...i.map(e=>e.status),...a.map(e=>e.status)]),s=[...r,...i,...a].filter(e=>pT(e.status)).length;return{rows:r,runRows:i,taskRows:a,summary:o,total:r.length+i.length+a.length,activeCount:s}}renderActivityPanel(e){let t=_T(this.activityFilter,e),n=e.activeCount===0&&this.activityScope===`active`?`empty-active`:this.activityScope,r=uT([...e.rows.map((e,t)=>({kind:`subagents`,index:t,status:e.status,row:e})),...e.runRows.map((e,t)=>({kind:`runs`,index:t,status:e.status,startedAt:e.run.startedAt,row:e})),...e.taskRows.map((e,t)=>({kind:`tasks`,index:t,status:e.status,startedAt:e.task.startedAt,row:e}))]).filter(e=>t===`all`||t===e.kind),i=r.filter(e=>n===`all`||!mT(e.status)),a=r.filter(e=>mT(e.status)).length;return g`
3151
3173
  <div class="subagents-list" id="session-activity-list" role="tabpanel" aria-labelledby="drawer-tab-activity">
3152
- ${e.total===0||n===`empty-active`?g`<p class="drawer-hint">${_T}</p>`:null}
3174
+ ${e.total===0||n===`empty-active`?g`<p class="drawer-hint">${vT}</p>`:null}
3153
3175
  ${this.renderActivityFilters(e,t)}
3154
3176
  ${n===`empty-active`?g`<p class="activity-empty">Nothing running right now.</p>`:null}
3155
3177
  ${i.map(e=>this.renderActivityEntry(e))}
@@ -3221,7 +3243,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3221
3243
  <div class="notification-metadata">
3222
3244
  <strong class="notification-severity">${n}</strong>
3223
3245
  <span aria-hidden="true">·</span>
3224
- <time datetime=${t.receivedAt}>${Bw.format(new Date(t.receivedAt))}</time>
3246
+ <time datetime=${t.receivedAt}>${Vw.format(new Date(t.receivedAt))}</time>
3225
3247
  </div>
3226
3248
  <p class="notification-message" dir="auto">${t.message}</p>
3227
3249
  ${r===void 0?null:g`<p class="notification-truncated">${r}</p>`}
@@ -3240,15 +3262,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3240
3262
  title="Dismiss notification"
3241
3263
  ?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
3242
3264
  @click=${()=>{this.dismissNotification(t.id)}}
3243
- >${Uw()}</button>
3265
+ >${Ww()}</button>
3244
3266
  </div>
3245
3267
  </article>
3246
3268
  `})}
3247
3269
  </div>
3248
3270
  `}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`
3249
- <div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${qS(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Yf(e)}</span>`)}</div>
3250
- <div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${qS(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Yf(e)}</span>`)}</div>
3251
- `}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=$f(t.notifications,e),r=ep(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=ep(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===ep(r)&&Xf(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||ep(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}Xf(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=nT(this.status);return!this.warningsVisible||e.length===0?null:g`
3271
+ <div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${dC(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Yf(e)}</span>`)}</div>
3272
+ <div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${dC(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Yf(e)}</span>`)}</div>
3273
+ `}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=$f(t.notifications,e),r=ep(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=ep(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===ep(r)&&Xf(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||ep(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}Xf(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=rT(this.status);return!this.warningsVisible||e.length===0?null:g`
3252
3274
  <aside class="session-warnings" role="alert" aria-live="polite">
3253
3275
  ${this.onToggleWarnings===void 0?null:g`
3254
3276
  <div class="session-warnings-controls">
@@ -3305,12 +3327,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3305
3327
  <img class="image-zoom-full" src=${this.zoomedImage.src} alt=${this.zoomedImage.alt} />
3306
3328
  `}
3307
3329
  </dialog>
3308
- `}transcriptMessages(){return Zl(this.messages,[...this.clientQueuedMessages,...this.status?.queuedMessages??[]])}queueGrew(e){let t=Vw(e)?.queuedMessages?.length??0;return(this.status?.queuedMessages??[]).length>t}groupedMessages(){let e=this.transcriptMessages();if(this.groupedMessagesInput===e&&this.groupedMessagesStart===this.messageStart)return this.groupedMessagesCache;let t=this.groupedMessagesInput;if(this.groupedMessagesStart===this.messageStart&&t!==void 0){let n=sC(t,this.groupedMessagesCache,e);if(n!==void 0)return this.groupedMessagesInput=e,this.groupedMessagesCache=n,n}return this.groupedMessagesInput=e,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=nC(e,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`}syncTurnClock(){if(!this.isSessionLive()){this.turnStartedAtMs=void 0,this.stopTurnClock();return}this.turnStartedAtMs??=Date.now(),this.turnNowMs=Date.now(),this.turnClockTimer===void 0&&(this.turnClockTimer=window.setInterval(()=>{this.turnNowMs=Date.now()},1e3))}stopTurnClock(){this.turnClockTimer!==void 0&&(window.clearInterval(this.turnClockTimer),this.turnClockTimer=void 0)}renderActivityDock(){if(this.pendingAsk!==void 0)return null;if(this.isSendingPrompt)return g`
3330
+ `}transcriptMessages(){return Zl(this.messages,[...this.clientQueuedMessages,...this.status?.queuedMessages??[]])}queueGrew(e){let t=Hw(e)?.queuedMessages?.length??0;return(this.status?.queuedMessages??[]).length>t}groupedMessages(){let e=this.transcriptMessages();if(this.groupedMessagesInput===e&&this.groupedMessagesStart===this.messageStart)return this.groupedMessagesCache;let t=this.groupedMessagesInput;if(this.groupedMessagesStart===this.messageStart&&t!==void 0){let n=TC(t,this.groupedMessagesCache,e);if(n!==void 0)return this.groupedMessagesInput=e,this.groupedMessagesCache=n,n}return this.groupedMessagesInput=e,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=bC(e,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`}syncTurnClock(){if(!this.isSessionLive()){this.turnStartedAtMs=void 0,this.stopTurnClock();return}this.turnStartedAtMs??=Date.now(),this.turnNowMs=Date.now(),this.turnClockTimer===void 0&&(this.turnClockTimer=window.setInterval(()=>{this.turnNowMs=Date.now()},1e3))}stopTurnClock(){this.turnClockTimer!==void 0&&(window.clearInterval(this.turnClockTimer),this.turnClockTimer=void 0)}renderActivityDock(){if(this.pendingAsk!==void 0)return null;if(this.isSendingPrompt)return g`
3309
3331
  <div class="activity-dock sending" aria-live="polite">
3310
3332
  <span class="state-dots"><span class="state-dot"></span><span class="state-dot"></span><span class="state-dot"></span></span>
3311
3333
  <span class="activity-text">Sending your message…</span>
3312
3334
  </div>
3313
- `;let e=this.activityState();if(e===void 0)return null;let t=this.activityCategory(e),n=vT(this.activityPanelState());if(n!==void 0&&(t===`idle`||t===void 0))return g`
3335
+ `;let e=this.activityState();if(e===void 0)return null;let t=this.activityCategory(e),n=yT(this.activityPanelState());if(n!==void 0&&(t===`idle`||t===void 0))return g`
3314
3336
  <button
3315
3337
  type="button"
3316
3338
  class="activity-dock background"
@@ -3322,13 +3344,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3322
3344
  <span class="activity-text">${n}</span>
3323
3345
  <span class="subagent-chevron" aria-hidden="true">›</span>
3324
3346
  </button>
3325
- `;let r=t===`working`?dT(this.turnStartedAtMs,this.turnNowMs):void 0;return g`
3347
+ `;let r=t===`working`?fT(this.turnStartedAtMs,this.turnNowMs):void 0;return g`
3326
3348
  <div class=${`activity-dock ${t??``}${r?.long===!0?` long-running`:``}`} aria-live="polite">
3327
3349
  ${t===`working`?g`<span class="state-dots"><span class="state-dot"></span><span class="state-dot"></span><span class="state-dot"></span></span>`:g`<span class="dot"></span>`}
3328
3350
  <span class="activity-text">${this.activityText(e)}</span>
3329
3351
  ${r===void 0?null:g`<span class="activity-elapsed" aria-hidden="true">${r.text}</span>`}
3330
3352
  </div>
3331
- `}revealActivity(){let e=this.topDrawerKey(),t=new Set(this.collapsedTopDrawerKeys);t.delete(e);let n=new Set(this.expandedTopDrawerKeys);n.add(e),this.collapsedTopDrawerKeys=t,this.expandedTopDrawerKeys=n,this.topDrawerTab=`activity`,this.activityScope=`active`}renderDeliveryMark(e){let t=e.meta?.delivery;if(t===void 0)return null;let n=qw(t);return g`
3353
+ `}revealActivity(){let e=this.topDrawerKey(),t=new Set(this.collapsedTopDrawerKeys);t.delete(e);let n=new Set(this.expandedTopDrawerKeys);n.add(e),this.collapsedTopDrawerKeys=t,this.expandedTopDrawerKeys=n,this.topDrawerTab=`activity`,this.activityScope=`active`}renderDeliveryMark(e){let t=e.meta?.delivery;if(t===void 0)return null;let n=Jw(t);return g`
3332
3354
  <div class=${`delivery-mark ${n.tone}`} role="status" aria-label=${n.label}>
3333
3355
  <span class="delivery-glyph" aria-hidden="true">${n.glyph}</span>
3334
3356
  <span class="delivery-text">${n.text}</span>
@@ -3348,7 +3370,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3348
3370
  .onSubmit=${this.onSubmitAsk}
3349
3371
  ></ask-user-card>
3350
3372
  `}renderExtensionDialogs(){let e=this.pendingDialogs[0];if(e===void 0&&this.closedDialogs.length===0)return null;let t=this.pendingDialogs.length-1;return g`
3351
- ${qS(this.closedDialogs,e=>e.dialog.dialogId,e=>g`
3373
+ ${dC(this.closedDialogs,e=>e.dialog.dialogId,e=>g`
3352
3374
  <extension-dialog-card
3353
3375
  class="closed-dialog-card"
3354
3376
  data-scroll-anchor-id=${`closed-dialog:${e.dialog.dialogId}`}
@@ -3372,7 +3394,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3372
3394
  <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
3373
3395
  ${this.pendingMessageCount>0?g`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?`message`:`messages`}</small>`:null}
3374
3396
  </aside>
3375
- `: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`}activityCategory(e){return this.activity?.phase===`error`?`error`:e===`idle`||e===`undefined`?Sm(this.status)?`asking`:`idle`:Sm(this.status)?`asking`:`working`}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(){if(!this.messages.length||this.messageTotal<=0)return null;let e=this.conversationDisplayTotal();return g`<conversation-meter .positionPercent=${this.conversationPositionPercent(e)} .loadedPercent=${this.hasMore?Gw(this.messages.length/e*100):100}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;let t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart;return Gw(Kw(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`
3397
+ `: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`}activityCategory(e){return this.activity?.phase===`error`?`error`:e===`idle`||e===`undefined`?Sm(this.status)?`asking`:`idle`:Sm(this.status)?`asking`:`working`}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(){if(!this.messages.length||this.messageTotal<=0)return null;let e=this.conversationDisplayTotal();return g`<conversation-meter .positionPercent=${this.conversationPositionPercent(e)} .loadedPercent=${this.hasMore?Kw(this.messages.length/e*100):100}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;let t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart;return Kw(qw(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`
3376
3398
  <div class="history-boundary">
3377
3399
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
3378
3400
  <span>Scroll up to load earlier messages</span>
@@ -3385,7 +3407,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3385
3407
  ${e.parts.map(t=>this.renderPart(t,e))}
3386
3408
  ${this.renderDeliveryMark(e)}
3387
3409
  </article>
3388
- `}renderToolImageOutput(e,t,n){let r=Yw(n);return g`
3410
+ `}renderToolImageOutput(e,t,n){let r=Xw(n);return g`
3389
3411
  ${this.renderScrollMarker(this.messageScrollMarkerId(t))}
3390
3412
  <article class="msg tool-image-output" data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
3391
3413
  ${this.renderMessageHeader(e,String(t),r)}
@@ -3393,10 +3415,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3393
3415
  </article>
3394
3416
  `}isToolExecutionOnlyMessage(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`toolExecution`)}isAskUserRecordOnlyMessage(e){return e.parts.length>0&&e.parts.every(e=>e.type===`askUserRecord`)}renderMessageGroup(e,t,n,r){let i=this.groupDisclosureKey(t,n,r),a=this.disclosures.isOpen(i,r);return g`
3395
3417
  ${this.renderScrollMarker(this.groupScrollMarkerId(n))}
3396
- <details class=${eT(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
3418
+ <details class=${tT(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
3397
3419
  <summary>
3398
- <b class="label">${tT(r)}</b>
3399
- <span>${rC(e)}</span>
3420
+ <b class="label">${nT(r)}</b>
3421
+ <span>${xC(e)}</span>
3400
3422
  </summary>
3401
3423
  ${a?this.renderMessageGroupBody(e,t):null}
3402
3424
  </details>
@@ -3419,7 +3441,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3419
3441
  </div>
3420
3442
  `}queueEntryFor(e){let t=e.meta?.delivery?.clientMessageId;if(t===void 0)return;let n=this.status?.queuedMessages??[],r=n.find(e=>e.clientMessageId===t);if(r!==void 0)return r;let i=/^queued:([^:]+):(.*)$/.exec(t);if(i===null)return;let[,a,o]=i;return n.find(e=>e.kind===a&&e.text===o)}isQueuedLine(e){return this.queueEntryFor(e)!==void 0}renderQueuedBubbleRecall(e){if(this.onRecallQueuedMessage===void 0)return null;let t=this.queueEntryFor(e);return t===void 0?null:g`<button type="button" class="msg-action" data-action="recall" title="Recall: take this message back and put it in the composer" aria-label="Recall this queued message into the composer" @click=${()=>{this.onRecallQueuedMessage?.(t)}}>
3421
3443
  <span aria-hidden="true">↩</span>
3422
- </button>`}renderMessageActions(e,t){let n=this.onResendMessage!==void 0&&HC(e),r=this.renderQueuedBubbleRecall(e);if(!this.isCopyableMessage(e)&&!n&&r===null)return null;let i=this.copiedMessageKey===t;return g`
3444
+ </button>`}renderMessageActions(e,t){let n=this.onResendMessage!==void 0&&UC(e),r=this.renderQueuedBubbleRecall(e);if(!this.isCopyableMessage(e)&&!n&&r===null)return null;let i=this.copiedMessageKey===t;return g`
3423
3445
  <div class="msg-actions" aria-label="Message actions">
3424
3446
  ${r}
3425
3447
  ${n?g`<button type="button" class="msg-action" title="Edit and send again" aria-label="Put this message back in the composer to send again" @click=${t=>{this.resendMessage(e,t)}}>
@@ -3429,9 +3451,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3429
3451
  <span aria-hidden="true">${i?`✓`:`⧉`}</span>
3430
3452
  </button>`:null}
3431
3453
  </div>
3432
- `}resendMessage(e,t){t.stopPropagation();let n=UC(e);n!==void 0&&this.onResendMessage?.(n)}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(`
3454
+ `}resendMessage(e,t){t.stopPropagation();let n=WC(e);n!==void 0&&this.onResendMessage?.(n)}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(`
3433
3455
 
3434
- `);return this.messageCopyTextCache.set(e,n),n}async copyNotification(e){if(!await Ex(e.message))return;let t=e.id;this.copiedNotificationId=t,setTimeout(()=>{this.copiedNotificationId===t&&(this.copiedNotificationId=void 0)},1200)}async copyMessage(e,t,n){n.stopPropagation(),await Ex(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=rT(e);return this.messageMetaCache.set(e,n),n}renderPart(e,t){if(e.type===`text`&&t?.role===`bash`)return g`<pre class="part shell-output">${e.text}</pre>`;if(e.type===`text`)return g`<formatted-text class="part" .text=${e.text}></formatted-text>`;if(e.type===`thinking`)return g`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
3456
+ `);return this.messageCopyTextCache.set(e,n),n}async copyNotification(e){if(!await Ex(e.message))return;let t=e.id;this.copiedNotificationId=t,setTimeout(()=>{this.copiedNotificationId===t&&(this.copiedNotificationId=void 0)},1200)}async copyMessage(e,t,n){n.stopPropagation(),await Ex(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=iT(e);return this.messageMetaCache.set(e,n),n}renderPart(e,t){if(e.type===`text`&&t?.role===`bash`)return g`<pre class="part shell-output">${e.text}</pre>`;if(e.type===`text`)return g`<formatted-text class="part" .text=${e.text}></formatted-text>`;if(e.type===`thinking`)return g`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
3435
3457
  <details class="part skill-invocation">
3436
3458
  <summary><b>[skill]</b> ${e.name}</summary>
3437
3459
  <small>${e.location}</small>
@@ -3448,46 +3470,46 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3448
3470
  .outcome=${e.outcome}
3449
3471
  .draftSessionId=${this.askDraftSessionId}
3450
3472
  ></ask-user-card>
3451
- `;if(e.type===`image`){let{src:t,alt:n}=Jw(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`
3473
+ `;if(e.type===`image`){let{src:t,alt:n}=Yw(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`
3452
3474
  <details class="part" ?open=${e.isError}>
3453
3475
  <summary>${e.isError?`✖`:`✓`} ${e.toolName} result</summary>
3454
3476
  <formatted-text .text=${e.text}></formatted-text>
3455
3477
  </details>
3456
- `: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.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&&gC({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||AC(e)}isAtBottom(){let e=this.chat;return!e||kC(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})}))}isNewPendingAsk(e){return this.pendingAsk!==void 0&&(typeof e!=`object`||!e||Reflect.get(e,`askId`)!==this.pendingAsk.askId)}isNewOpenDialog(e){let t=this.pendingDialogs[0];if(t===void 0)return!1;if(!Array.isArray(e))return!0;let n=e[0];return typeof n!=`object`||!n||Reflect.get(n,`dialogId`)!==t.dialogId}scrollToOpenAsk(){this.scrollToOpenAskFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenAskFrame=requestAnimationFrame(()=>{this.scrollToOpenAskFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenAskToTop()})}))}alignOpenAskToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > ask-user-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}scrollToOpenDialog(){this.scrollToOpenDialogFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenDialogFrame=requestAnimationFrame(()=>{this.scrollToOpenDialogFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenDialogToTop()})}))}alignOpenDialogToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > extension-dialog-card.open-dialog-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{if(this.pendingAsk!==void 0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenAskToTop()||this.pendingDialogs.length>0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenDialogToTop())return;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 cC(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(lC(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=Kw(n,0,Math.max(0,e-1));return}this.currentConversationIndex=Kw(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 NC(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??NC(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 Xw(e)}groupRenderKey(e){return Zw(e)}groupAnchorKey(e){return Zw(e)}eventAnchorKey(e){return Qw(e)}messageScrollMarkerId(e){return Xw(e)}groupScrollMarkerId(e){return $w(e)}static{this.styles=ag}};H([b({attribute:!1})],K.prototype,`messages`,void 0),H([b()],K.prototype,`sessionId`,void 0),H([b({type:Number})],K.prototype,`messageStart`,void 0),H([b({type:Number})],K.prototype,`messageEnd`,void 0),H([b({type:Number})],K.prototype,`messageTotal`,void 0),H([b({type:Boolean})],K.prototype,`hasMore`,void 0),H([b({type:Boolean})],K.prototype,`loadingMore`,void 0),H([b({type:Boolean})],K.prototype,`isSendingPrompt`,void 0),H([b({type:Boolean})],K.prototype,`isCompacting`,void 0),H([b({type:Number})],K.prototype,`pendingMessageCount`,void 0),H([b({attribute:!1})],K.prototype,`clientQueuedMessages`,void 0),H([b({attribute:!1})],K.prototype,`status`,void 0),H([b({attribute:!1})],K.prototype,`activity`,void 0),H([b({attribute:!1})],K.prototype,`pendingAsk`,void 0),H([b({attribute:!1})],K.prototype,`askDraftSessionId`,void 0),H([b({attribute:!1})],K.prototype,`onSubmitAsk`,void 0),H([b({attribute:!1})],K.prototype,`pendingDialogs`,void 0),H([b({attribute:!1})],K.prototype,`closedDialogs`,void 0),H([b({attribute:!1})],K.prototype,`onAnswerDialog`,void 0),H([b({attribute:!1})],K.prototype,`onCancelDialog`,void 0),H([b({attribute:!1})],K.prototype,`onDismissClosedDialog`,void 0),H([b({attribute:!1})],K.prototype,`onResendMessage`,void 0),H([b({attribute:!1})],K.prototype,`notificationInbox`,void 0),H([b({attribute:!1})],K.prototype,`subagents`,void 0),H([b({attribute:!1})],K.prototype,`subagentRuns`,void 0),H([b({attribute:!1})],K.prototype,`backgroundTasks`,void 0),H([b({attribute:!1})],K.prototype,`onOpenBackgroundTask`,void 0),H([b({attribute:!1})],K.prototype,`onOpenSubagentRun`,void 0),H([b({attribute:!1})],K.prototype,`onOpenSubagent`,void 0),H([b({attribute:!1})],K.prototype,`onClearServerQueue`,void 0),H([b({attribute:!1})],K.prototype,`onRecallQueuedMessage`,void 0),H([b({attribute:!1})],K.prototype,`onDismissWarning`,void 0),H([b({attribute:!1})],K.prototype,`onDismissNotification`,void 0),H([b({attribute:!1})],K.prototype,`onDismissAllNotifications`,void 0),H([b({type:Boolean})],K.prototype,`warningsVisible`,void 0),H([b({attribute:!1})],K.prototype,`onToggleWarnings`,void 0),H([b({attribute:!1})],K.prototype,`onLoadMore`,void 0),H([b({attribute:!1})],K.prototype,`activityOutput`,void 0),H([b({attribute:!1})],K.prototype,`onCloseActivityOutput`,void 0),H([S(`.chat`)],K.prototype,`chat`,void 0),H([S(`.drawer-tabs`)],K.prototype,`drawerTabs`,void 0),H([S(`dialog.image-zoom`)],K.prototype,`imageZoomDialog`,void 0),H([S(`dialog.activity-output`)],K.prototype,`activityOutputDialog`,void 0),H([x()],K.prototype,`pinnedToBottom`,void 0),H([x()],K.prototype,`zoomedImage`,void 0),H([x()],K.prototype,`expandedMetaKey`,void 0),H([x()],K.prototype,`copiedNotificationId`,void 0),H([x()],K.prototype,`copiedMessageKey`,void 0),H([x()],K.prototype,`currentConversationIndex`,void 0),H([x()],K.prototype,`collapsedTopDrawerKeys`,void 0),H([x()],K.prototype,`expandedTopDrawerKeys`,void 0),H([b({attribute:!1})],K.prototype,`goals`,void 0),H([b({attribute:!1})],K.prototype,`onRunGoalCommand`,void 0),H([x()],K.prototype,`topDrawerTab`,void 0),H([x()],K.prototype,`activityFilter`,void 0),H([x()],K.prototype,`activityScope`,void 0),H([x()],K.prototype,`turnStartedAtMs`,void 0),H([x()],K.prototype,`turnNowMs`,void 0),H([x()],K.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),H([x()],K.prototype,`loadMoreRequested`,void 0),K=H([y(`chat-view`)],K);function oT(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${String(t)}s`;let n=Math.floor(t/60);return n<60?`${String(n)}m ${String(t%60)}s`:`${String(Math.floor(n/60))}h ${String(n%60)}m`}function sT(e){return e.map(e=>{let t=e.status===`running`?`Running`:e.status===`done`?`Done`:e.status===`failed`?`Failed`:e.status===`lost`?`Stopped`:`Unknown`,n=oT(e.elapsedMs),r=e.status===`running`?e.lastActivity??`working`:e.task??``,i=nw(e.model);return{run:e,status:e.status===`lost`?`failed`:e.status,statusLabel:t,duration:n,detail:r,...i===void 0?{}:{modelLabel:i.label,modelTitle:e.model??i.label},ariaLabel:`${t} ${e.agent} subagent, ${n}`+(i===void 0?``:`, on ${i.label}`)+(r===``?``:`, ${r}`)}})}function cT(e){return e.map(e=>{let t=e.status===`running`?`running`:e.status===`completed`?`done`:e.status===`failed`||e.status===`killed`||e.status===`lost`?`failed`:`unknown`,n=e.status===`completed`?`Done`:e.status===`running`?`Running`:e.status===`lost`?`Lost`:e.status.charAt(0).toUpperCase()+e.status.slice(1),r=oT(e.durationMs??0),i=t===`running`?e.command.slice(0,60):e.exitCode===void 0?``:`exit ${String(e.exitCode)}`;return{task:e,status:t,statusLabel:n,duration:r,detail:i,ariaLabel:`${n} background task ${e.name}, ${r}${i===``?``:`, ${i}`}`}})}function lT(e){return[...e].sort((e,t)=>{let n=Number(fT(t.status))-Number(fT(e.status));if(n!==0)return n;let r=Number(pT(e.status))-Number(pT(t.status));if(r!==0)return r;let i=(t.startedAt??``).localeCompare(e.startedAt??``);return i===0?e.kind.localeCompare(t.kind):i})}var uT=600*1e3;function dT(e,t){if(e===void 0)return;let n=Math.max(0,t-e);if(!(n<5e3))return{text:oT(n),long:n>=uT}}function fT(e){return e===`working`||e===`running`}function pT(e){return e===`done`||e===`failed`||e===`error`||e===`lost`}function mT(e){return e.active>0?`Activity · ${String(e.active)} running`:`Activity (${String(e.total)})`}function hT(e){let t=[{id:`subagents`,label:`Subagents`,count:e.rows.length},{id:`runs`,label:`Agent runs`,count:e.runRows.length},{id:`tasks`,label:`Tasks`,count:e.taskRows.length}].filter(e=>e.count>0);return t.length<=1?t.length===0?[]:t:[{id:`all`,label:`All`,count:e.rows.length+e.runRows.length+e.taskRows.length},...t]}function gT(e,t){return e===`subagents`&&t.rows.length>0?`subagents`:e===`runs`&&t.runRows.length>0?`runs`:e===`tasks`&&t.taskRows.length>0?`tasks`:`all`}var _T=`Work this chat started in the background: subagents, agent tool runs and terminal tasks. Open one to read its output.`;function vT(e){if(e===void 0)return;let t=[...e.rows,...e.runRows,...e.taskRows].filter(e=>e.status===`working`||e.status===`running`).length;if(t!==0)return t===1?`idle · 1 background run`:`idle · ${String(t)} background runs`}function yT(){return!1}function bT(e,t){return t===`activity`&&e.activity?`activity`:t===`notifications`&&e.notifications?`notifications`:t===`goals`&&e.goals===!0?`goals`:e.notifications?`notifications`:e.activity?`activity`:e.goals===!0?`goals`:`activity`}function xT(e){let t=e.filter(e=>e===`working`||e===`running`).length,n=e.filter(e=>e===`error`||e===`failed`).length,r=e.length-t-n,i=[];return t>0&&i.push(`${String(t)} running`),n>0&&i.push(`${String(n)} failed`),r>0&&i.push(`${String(r)} done`),{label:i.join(` · `),working:t>0,failed:n>0}}function ST(e){return e===``?`Unknown`:e.charAt(0).toUpperCase()+e.slice(1)}function CT(e){return e.map(e=>{let t=e.status,n=e.sessionId.slice(-8),r=ST(t);return{subagent:e,shortId:n,status:t,statusLabel:r,cwd:e.cwd,ariaLabel:`${r} subagent ${n}`}})}var wT=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function TT(e){return typeof e==`string`&&wT.has(e)}function ET(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 DT=`application/octet-stream`,OT=`Failed to read an attachment.`;async function kT(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(NT(i,e))}catch{r=OT}return{attachments:n,...r===void 0?{}:{error:r}}}function AT(e){return e.kind===`image`&&TT(e.mimeType)}function jT(e){return e.every(e=>AT(e))}function MT(e,t){return jT(t)?e:`folder`}function NT(e,t){return TT(e.type)?{kind:`image`,name:FT(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:FT(e),mimeType:PT(e),data:t,size:e.size}}function PT(e){let t=e.type.trim();return t===``?DT:t}function FT(e){return e.name===``?TT(e.type)?`pasted-image.${ET(e.type)}`:`pasted-file.bin`:e.name}var IT=50,LT=`pi-web:prompt-history:`;function RT(e){return`${LT}${e}`}function zT(e){try{let t=localStorage.getItem(RT(e));if(t===null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e.trim()!==``):[]}catch{return[]}}function BT(e,t){try{localStorage.setItem(RT(e),JSON.stringify(t.slice(0,IT)))}catch{}}function VT(e,t){let n=t.trim();if(n===``)return zT(e);let r=[n,...zT(e).filter(e=>e!==n)].slice(0,IT);return BT(e,r),r}function HT(e,t){let n=zT(e),r=t.trim().toLowerCase();if(r===``)return n;let i=r.split(/\s+/u).filter(Boolean);return n.filter(e=>{let t=e.toLowerCase();return i.every(e=>t.includes(e)||UT(e,t))})}function UT(e,t){let n=0;for(let r of e){if(n=t.indexOf(r,n),n===-1)return!1;n+=r.length}return!0}function WT(e){return e===`older`?1:-1}var GT=`(pointer: coarse), (max-width: 760px)`,KT=`pi-web.promptEnterPreference`;function qT(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(GT):void 0}function JT(e){return e===`send`||e===`newline`?e:`auto`}function YT(e=eE()){if(e===void 0)return`auto`;try{return JT(e.getItem(KT))}catch{return`auto`}}function XT(e,t=eE()){if(t!==void 0)try{t.setItem(KT,e)}catch{}}function ZT(e=qT(),t=YT()){return t===`send`||t!==`newline`&&e?.matches!==!0}function QT(e,t,n=qT()){return e?n?.matches!==!0||t:!1}function $T(e,t=qT(),n=YT()){let r=ZT(t,n);return e?!r:r}function eE(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var tE=100;function nE(){let e,t,n,r,i=[],a=()=>{r!==void 0&&(window.clearInterval(r),r=void 0),e?.getTracks().forEach(e=>{e.stop()}),e=void 0,n?.close().catch(()=>void 0),n=void 0,t=void 0};return{async start(a){i=[],e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e),t.addEventListener(`dataavailable`,e=>{e.data.size>0&&i.push(e.data)}),t.start(),n=new AudioContext;let o=n.createMediaStreamSource(e),s=n.createAnalyser();s.fftSize=512,o.connect(s);let c=new Uint8Array(s.fftSize);r=window.setInterval(()=>{s.getByteTimeDomainData(c),a(rE(c),tE)},tE)},stop(){let e=t;return e===void 0?(a(),Promise.resolve(new Blob([]))):new Promise(t=>{e.addEventListener(`stop`,()=>{let e=i[0]?.type??`audio/webm`,n=new Blob(i,{type:e});a(),t(n)},{once:!0}),e.stop()})},cancel(){i=[],t?.state===`recording`&&t.stop(),a()}}}function rE(e){let t=0;for(let n of e){let e=Math.abs(n-128)/128;e>t&&(t=e)}return t}function iE(e){return e!==void 0&&e.endpoint.trim()!==``}async function aE(e,t,n){if(!iE(t))return{ok:!1,message:`Dictation is not configured.`};if(e.size===0)return{ok:!1,message:`Nothing was recorded.`};let r=new FormData;r.append(`file`,e,`speech.webm`),t.model!==void 0&&t.model!==``&&r.append(`model`,t.model),t.language!==void 0&&t.language!==``&&r.append(`language`,t.language);let i;try{i=await n.fetch(t.endpoint,{method:`POST`,body:r,...n.signal===void 0?{}:{signal:n.signal}})}catch(e){return{ok:!1,message:`Could not reach the transcription service: ${cE(e)}`}}if(!i.ok)return{ok:!1,message:`Transcription failed (${String(i.status)}).`};let a;try{a=await i.json()}catch{return{ok:!1,message:`The transcription service returned a response that could not be read.`}}let o=oE(a);if(o===void 0)return{ok:!1,message:`The transcription service returned no text.`};let s=o.trim();return s===``?{ok:!1,message:`No speech was recognised.`}:{ok:!0,text:s}}function oE(e){if(typeof e==`string`)return e;let t=sE(e);if(t===void 0)return;for(let e of[`text`,`transcript`,`transcription`]){let n=t[e];if(typeof n==`string`)return n}let n=t.segments;if(!Array.isArray(n))return;let r=n.map(e=>sE(e)?.text).filter(e=>typeof e==`string`).join(` `);return r.trim()===``?void 0:r}function sE(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function cE(e){return e instanceof Error?e.message:String(e)}var lE={"openai-realtime":`append`,deepgram:`replace`,"azure-speech":`replace`};function uE(e){if(e===void 0)return{kind:`unavailable`,reason:`Live transcription is not configured.`};if(e.protocol===`browser`)return{kind:`browser`};let t=e.url?.trim();if(t===void 0||t===``)return{kind:`unavailable`,reason:`Streaming transcription needs a socket url.`};let n=e.tokenEndpoint?.trim();return n===void 0||n===``?{kind:`unavailable`,reason:`Streaming transcription needs a token endpoint so the account key stays on the server.`}:{kind:`socket`,protocol:e.protocol,url:t,tokenEndpoint:n,deltaMode:lE[e.protocol]}}var dE={trailingSilenceMs:900,speechThreshold:.02,maxUtteranceMs:12e4};function fE(e,t,n,r=dE){if(e.kind!==`listening`&&e.kind!==`speaking`&&e.kind!==`trailing`)return e;if(n>=r.maxUtteranceMs)return e.kind===`listening`?{kind:`idle`}:{kind:`transcribing`};let i=t.level>=r.speechThreshold;if(e.kind===`listening`)return i?{kind:`speaking`}:e;if(e.kind===`speaking`)return i?e:{kind:`trailing`,silenceMs:t.elapsedMs};if(i)return{kind:`speaking`};let a=e.silenceMs+t.elapsedMs;return a>=r.trailingSilenceMs?{kind:`transcribing`}:{kind:`trailing`,silenceMs:a}}function pE(e){switch(e.kind){case`idle`:case`denied`:case`error`:return{kind:`listening`};case`listening`:return{kind:`idle`};case`speaking`:case`trailing`:return{kind:`transcribing`};case`transcribing`:case`unavailable`:return e}}function mE(e){return e.kind===`listening`||e.kind===`speaking`||e.kind===`trailing`}function hE(e,t){switch(e.kind){case`idle`:return t?.streaming===!0?`Dictate live`:`Dictate`;case`listening`:return`Listening…`;case`speaking`:return`Listening…`;case`trailing`:return`Listening…`;case`transcribing`:return`Transcribing…`;case`denied`:return`Microphone permission denied`;case`unavailable`:return e.reason;case`error`:return e.message}}var gE=class{constructor(e,t){this.deps=e,this.callbacks=t,this.state={kind:`idle`},this.elapsedMs=0}getState(){return this.state}async toggle(e){if(!iE(e)){this.setState({kind:`unavailable`,reason:`Dictation is not configured.`});return}let t=pE(this.state);if(t.kind===`listening`&&!mE(this.state)){await this.startListening(e);return}if(t.kind===`idle`){this.deps.recorder.cancel(),this.setState({kind:`idle`});return}if(t.kind===`transcribing`){await this.finish(e);return}this.setState(t)}async startListening(e){this.activeConfig=e,this.elapsedMs=0,this.setState({kind:`listening`});try{await this.deps.recorder.start((e,t)=>{this.onFrame(e,t)})}catch(e){this.setState(_E(e)?{kind:`denied`}:{kind:`error`,message:`Microphone unavailable: ${vE(e)}`})}}onFrame(e,t){if(!mE(this.state))return;this.elapsedMs+=t;let n=fE(this.state,{level:e,elapsedMs:t},this.elapsedMs,this.deps.captureConfig??dE);if(n!==this.state){if(n.kind===`transcribing`){this.finish(this.activeConfig);return}n.kind===`idle`&&this.deps.recorder.cancel(),this.setState(n)}}async finish(e){this.setState({kind:`transcribing`});let t;try{t=await this.deps.recorder.stop()}catch(e){this.setState({kind:`error`,message:`Recording failed: ${vE(e)}`});return}if(!iE(e)){this.setState({kind:`unavailable`,reason:`Dictation is not configured.`});return}let n=await(this.deps.transcribe??aE)(t,e,{fetch:this.deps.fetch??globalThis.fetch});if(!n.ok){this.setState({kind:`error`,message:n.message});return}this.callbacks.onTranscript(n.text),this.setState({kind:`idle`})}setState(e){this.state=e,this.callbacks.onState(e)}};function _E(e){if(typeof e!=`object`||!e)return!1;let t=`name`in e?e.name:void 0;return t===`NotAllowedError`||t===`SecurityError`}function vE(e){return e instanceof Error?e.message:String(e)}function yE(){return Ye`
3478
+ `: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.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.jumpToBottomVisible=eC(e),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&&PC({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||JS(e)}isAtBottom(){let e=this.chat;return!e||qS(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})}))}isNewPendingAsk(e){return this.pendingAsk!==void 0&&(typeof e!=`object`||!e||Reflect.get(e,`askId`)!==this.pendingAsk.askId)}isNewOpenDialog(e){let t=this.pendingDialogs[0];if(t===void 0)return!1;if(!Array.isArray(e))return!0;let n=e[0];return typeof n!=`object`||!n||Reflect.get(n,`dialogId`)!==t.dialogId}scrollToOpenAsk(){this.scrollToOpenAskFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenAskFrame=requestAnimationFrame(()=>{this.scrollToOpenAskFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenAskToTop()})}))}alignOpenAskToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > ask-user-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}scrollToOpenDialog(){this.scrollToOpenDialogFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenDialogFrame=requestAnimationFrame(()=>{this.scrollToOpenDialogFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenDialogToTop()})}))}alignOpenDialogToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > extension-dialog-card.open-dialog-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{if(this.pendingAsk!==void 0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenAskToTop()||this.pendingDialogs.length>0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenDialogToTop())return;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 EC(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(DC(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=qw(n,0,Math.max(0,e-1));return}this.currentConversationIndex=qw(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 ZS(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??ZS(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 Zw(e)}groupRenderKey(e){return Qw(e)}groupAnchorKey(e){return Qw(e)}eventAnchorKey(e){return $w(e)}messageScrollMarkerId(e){return Zw(e)}groupScrollMarkerId(e){return eT(e)}static{this.styles=ag}};H([b({attribute:!1})],K.prototype,`messages`,void 0),H([b()],K.prototype,`sessionId`,void 0),H([b({type:Number})],K.prototype,`messageStart`,void 0),H([b({type:Number})],K.prototype,`messageEnd`,void 0),H([b({type:Number})],K.prototype,`messageTotal`,void 0),H([b({type:Boolean})],K.prototype,`hasMore`,void 0),H([b({type:Boolean})],K.prototype,`loadingMore`,void 0),H([b({type:Boolean})],K.prototype,`isSendingPrompt`,void 0),H([b({type:Boolean})],K.prototype,`isCompacting`,void 0),H([b({type:Number})],K.prototype,`pendingMessageCount`,void 0),H([b({attribute:!1})],K.prototype,`clientQueuedMessages`,void 0),H([b({attribute:!1})],K.prototype,`status`,void 0),H([b({attribute:!1})],K.prototype,`activity`,void 0),H([b({attribute:!1})],K.prototype,`pendingAsk`,void 0),H([b({attribute:!1})],K.prototype,`askDraftSessionId`,void 0),H([b({attribute:!1})],K.prototype,`onSubmitAsk`,void 0),H([b({attribute:!1})],K.prototype,`pendingDialogs`,void 0),H([b({attribute:!1})],K.prototype,`closedDialogs`,void 0),H([b({attribute:!1})],K.prototype,`onAnswerDialog`,void 0),H([b({attribute:!1})],K.prototype,`onCancelDialog`,void 0),H([b({attribute:!1})],K.prototype,`onDismissClosedDialog`,void 0),H([b({attribute:!1})],K.prototype,`onResendMessage`,void 0),H([b({attribute:!1})],K.prototype,`notificationInbox`,void 0),H([b({attribute:!1})],K.prototype,`subagents`,void 0),H([b({attribute:!1})],K.prototype,`subagentRuns`,void 0),H([b({attribute:!1})],K.prototype,`backgroundTasks`,void 0),H([b({attribute:!1})],K.prototype,`onOpenBackgroundTask`,void 0),H([b({attribute:!1})],K.prototype,`onOpenSubagentRun`,void 0),H([b({attribute:!1})],K.prototype,`onOpenSubagent`,void 0),H([b({attribute:!1})],K.prototype,`onClearServerQueue`,void 0),H([b({attribute:!1})],K.prototype,`onRecallQueuedMessage`,void 0),H([b({attribute:!1})],K.prototype,`onDismissWarning`,void 0),H([b({attribute:!1})],K.prototype,`onDismissNotification`,void 0),H([b({attribute:!1})],K.prototype,`onDismissAllNotifications`,void 0),H([b({type:Boolean})],K.prototype,`warningsVisible`,void 0),H([b({attribute:!1})],K.prototype,`onToggleWarnings`,void 0),H([b({attribute:!1})],K.prototype,`onLoadMore`,void 0),H([b({attribute:!1})],K.prototype,`activityOutput`,void 0),H([b({attribute:!1})],K.prototype,`onCloseActivityOutput`,void 0),H([S(`.chat`)],K.prototype,`chat`,void 0),H([S(`.drawer-tabs`)],K.prototype,`drawerTabs`,void 0),H([S(`dialog.image-zoom`)],K.prototype,`imageZoomDialog`,void 0),H([S(`dialog.activity-output`)],K.prototype,`activityOutputDialog`,void 0),H([x()],K.prototype,`pinnedToBottom`,void 0),H([x()],K.prototype,`jumpToBottomVisible`,void 0),H([x()],K.prototype,`zoomedImage`,void 0),H([x()],K.prototype,`expandedMetaKey`,void 0),H([x()],K.prototype,`copiedNotificationId`,void 0),H([x()],K.prototype,`copiedMessageKey`,void 0),H([x()],K.prototype,`currentConversationIndex`,void 0),H([x()],K.prototype,`collapsedTopDrawerKeys`,void 0),H([x()],K.prototype,`expandedTopDrawerKeys`,void 0),H([b({attribute:!1})],K.prototype,`goals`,void 0),H([b({attribute:!1})],K.prototype,`onRunGoalCommand`,void 0),H([x()],K.prototype,`topDrawerTab`,void 0),H([x()],K.prototype,`activityFilter`,void 0),H([x()],K.prototype,`activityScope`,void 0),H([x()],K.prototype,`turnStartedAtMs`,void 0),H([x()],K.prototype,`turnNowMs`,void 0),H([x()],K.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),H([x()],K.prototype,`loadMoreRequested`,void 0),K=H([y(`chat-view`)],K);function sT(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${String(t)}s`;let n=Math.floor(t/60);return n<60?`${String(n)}m ${String(t%60)}s`:`${String(Math.floor(n/60))}h ${String(n%60)}m`}function cT(e){return e.map(e=>{let t=e.status===`running`?`Running`:e.status===`done`?`Done`:e.status===`failed`?`Failed`:e.status===`lost`?`Stopped`:`Unknown`,n=sT(e.elapsedMs),r=e.status===`running`?e.lastActivity??`working`:e.task??``,i=rw(e.model);return{run:e,status:e.status===`lost`?`failed`:e.status,statusLabel:t,duration:n,detail:r,...i===void 0?{}:{modelLabel:i.label,modelTitle:e.model??i.label},ariaLabel:`${t} ${e.agent} subagent, ${n}`+(i===void 0?``:`, on ${i.label}`)+(r===``?``:`, ${r}`)}})}function lT(e){return e.map(e=>{let t=e.status===`running`?`running`:e.status===`completed`?`done`:e.status===`failed`||e.status===`killed`||e.status===`lost`?`failed`:`unknown`,n=e.status===`completed`?`Done`:e.status===`running`?`Running`:e.status===`lost`?`Lost`:e.status.charAt(0).toUpperCase()+e.status.slice(1),r=sT(e.durationMs??0),i=t===`running`?e.command.slice(0,60):e.exitCode===void 0?``:`exit ${String(e.exitCode)}`;return{task:e,status:t,statusLabel:n,duration:r,detail:i,ariaLabel:`${n} background task ${e.name}, ${r}${i===``?``:`, ${i}`}`}})}function uT(e){return[...e].sort((e,t)=>{let n=Number(pT(t.status))-Number(pT(e.status));if(n!==0)return n;let r=Number(mT(e.status))-Number(mT(t.status));if(r!==0)return r;let i=(t.startedAt??``).localeCompare(e.startedAt??``);return i===0?e.kind.localeCompare(t.kind):i})}var dT=600*1e3;function fT(e,t){if(e===void 0)return;let n=Math.max(0,t-e);if(!(n<5e3))return{text:sT(n),long:n>=dT}}function pT(e){return e===`working`||e===`running`}function mT(e){return e===`done`||e===`failed`||e===`error`||e===`lost`}function hT(e){return e.active>0?`Activity · ${String(e.active)} running`:`Activity (${String(e.total)})`}function gT(e){let t=[{id:`subagents`,label:`Subagents`,count:e.rows.length},{id:`runs`,label:`Agent runs`,count:e.runRows.length},{id:`tasks`,label:`Tasks`,count:e.taskRows.length}].filter(e=>e.count>0);return t.length<=1?t.length===0?[]:t:[{id:`all`,label:`All`,count:e.rows.length+e.runRows.length+e.taskRows.length},...t]}function _T(e,t){return e===`subagents`&&t.rows.length>0?`subagents`:e===`runs`&&t.runRows.length>0?`runs`:e===`tasks`&&t.taskRows.length>0?`tasks`:`all`}var vT=`Work this chat started in the background: subagents, agent tool runs and terminal tasks. Open one to read its output.`;function yT(e){if(e===void 0)return;let t=[...e.rows,...e.runRows,...e.taskRows].filter(e=>e.status===`working`||e.status===`running`).length;if(t!==0)return t===1?`idle · 1 background run`:`idle · ${String(t)} background runs`}function bT(){return!1}function xT(e,t){return t===`activity`&&e.activity?`activity`:t===`notifications`&&e.notifications?`notifications`:t===`goals`&&e.goals===!0?`goals`:e.notifications?`notifications`:e.activity?`activity`:e.goals===!0?`goals`:`activity`}function ST(e){let t=e.filter(e=>e===`working`||e===`running`).length,n=e.filter(e=>e===`error`||e===`failed`).length,r=e.length-t-n,i=[];return t>0&&i.push(`${String(t)} running`),n>0&&i.push(`${String(n)} failed`),r>0&&i.push(`${String(r)} done`),{label:i.join(` · `),working:t>0,failed:n>0}}function CT(e){return e===``?`Unknown`:e.charAt(0).toUpperCase()+e.slice(1)}function wT(e){return e.map(e=>{let t=e.status,n=e.sessionId.slice(-8),r=CT(t);return{subagent:e,shortId:n,status:t,statusLabel:r,cwd:e.cwd,ariaLabel:`${r} subagent ${n}`}})}var TT=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function ET(e){return typeof e==`string`&&TT.has(e)}function DT(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 OT=`application/octet-stream`,kT=`Failed to read an attachment.`;async function AT(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(PT(i,e))}catch{r=kT}return{attachments:n,...r===void 0?{}:{error:r}}}function jT(e){return e.kind===`image`&&ET(e.mimeType)}function MT(e){return e.every(e=>jT(e))}function NT(e,t){return MT(t)?e:`folder`}function PT(e,t){return ET(e.type)?{kind:`image`,name:IT(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:IT(e),mimeType:FT(e),data:t,size:e.size}}function FT(e){let t=e.type.trim();return t===``?OT:t}function IT(e){return e.name===``?ET(e.type)?`pasted-image.${DT(e.type)}`:`pasted-file.bin`:e.name}var LT=50,RT=`pi-web:prompt-history:`;function zT(e){return`${RT}${e}`}function BT(e){try{let t=localStorage.getItem(zT(e));if(t===null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e.trim()!==``):[]}catch{return[]}}function VT(e,t){try{localStorage.setItem(zT(e),JSON.stringify(t.slice(0,LT)))}catch{}}function HT(e,t){let n=t.trim();if(n===``)return BT(e);let r=[n,...BT(e).filter(e=>e!==n)].slice(0,LT);return VT(e,r),r}function UT(e,t){let n=BT(e),r=t.trim().toLowerCase();if(r===``)return n;let i=r.split(/\s+/u).filter(Boolean);return n.filter(e=>{let t=e.toLowerCase();return i.every(e=>t.includes(e)||WT(e,t))})}function WT(e,t){let n=0;for(let r of e){if(n=t.indexOf(r,n),n===-1)return!1;n+=r.length}return!0}function GT(e){return e===`older`?1:-1}var KT=`(pointer: coarse), (max-width: 760px)`,qT=`pi-web.promptEnterPreference`;function JT(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(KT):void 0}function YT(e){return e===`send`||e===`newline`?e:`auto`}function XT(e=tE()){if(e===void 0)return`auto`;try{return YT(e.getItem(qT))}catch{return`auto`}}function ZT(e,t=tE()){if(t!==void 0)try{t.setItem(qT,e)}catch{}}function QT(e=JT(),t=XT()){return t===`send`||t!==`newline`&&e?.matches!==!0}function $T(e,t,n=JT()){return e?n?.matches!==!0||t:!1}function eE(e,t=JT(),n=XT()){let r=QT(t,n);return e?!r:r}function tE(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var nE=100;function rE(){let e,t,n,r,i=[],a=()=>{r!==void 0&&(window.clearInterval(r),r=void 0),e?.getTracks().forEach(e=>{e.stop()}),e=void 0,n?.close().catch(()=>void 0),n=void 0,t=void 0};return{async start(a){i=[],e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e),t.addEventListener(`dataavailable`,e=>{e.data.size>0&&i.push(e.data)}),t.start(),n=new AudioContext;let o=n.createMediaStreamSource(e),s=n.createAnalyser();s.fftSize=512,o.connect(s);let c=new Uint8Array(s.fftSize);r=window.setInterval(()=>{s.getByteTimeDomainData(c),a(iE(c),nE)},nE)},stop(){let e=t;return e===void 0?(a(),Promise.resolve(new Blob([]))):new Promise(t=>{e.addEventListener(`stop`,()=>{let e=i[0]?.type??`audio/webm`,n=new Blob(i,{type:e});a(),t(n)},{once:!0}),e.stop()})},cancel(){i=[],t?.state===`recording`&&t.stop(),a()}}}function iE(e){let t=0;for(let n of e){let e=Math.abs(n-128)/128;e>t&&(t=e)}return t}function aE(e){return e!==void 0&&e.endpoint.trim()!==``}async function oE(e,t,n){if(!aE(t))return{ok:!1,message:`Dictation is not configured.`};if(e.size===0)return{ok:!1,message:`Nothing was recorded.`};let r=new FormData;r.append(`file`,e,`speech.webm`),t.model!==void 0&&t.model!==``&&r.append(`model`,t.model),t.language!==void 0&&t.language!==``&&r.append(`language`,t.language);let i;try{i=await n.fetch(t.endpoint,{method:`POST`,body:r,...n.signal===void 0?{}:{signal:n.signal}})}catch(e){return{ok:!1,message:`Could not reach the transcription service: ${lE(e)}`}}if(!i.ok)return{ok:!1,message:`Transcription failed (${String(i.status)}).`};let a;try{a=await i.json()}catch{return{ok:!1,message:`The transcription service returned a response that could not be read.`}}let o=sE(a);if(o===void 0)return{ok:!1,message:`The transcription service returned no text.`};let s=o.trim();return s===``?{ok:!1,message:`No speech was recognised.`}:{ok:!0,text:s}}function sE(e){if(typeof e==`string`)return e;let t=cE(e);if(t===void 0)return;for(let e of[`text`,`transcript`,`transcription`]){let n=t[e];if(typeof n==`string`)return n}let n=t.segments;if(!Array.isArray(n))return;let r=n.map(e=>cE(e)?.text).filter(e=>typeof e==`string`).join(` `);return r.trim()===``?void 0:r}function cE(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function lE(e){return e instanceof Error?e.message:String(e)}var uE={"openai-realtime":`append`,deepgram:`replace`,"azure-speech":`replace`};function dE(e){if(e===void 0)return{kind:`unavailable`,reason:`Live transcription is not configured.`};if(e.protocol===`browser`)return{kind:`browser`};let t=e.url?.trim();if(t===void 0||t===``)return{kind:`unavailable`,reason:`Streaming transcription needs a socket url.`};let n=e.tokenEndpoint?.trim();return n===void 0||n===``?{kind:`unavailable`,reason:`Streaming transcription needs a token endpoint so the account key stays on the server.`}:{kind:`socket`,protocol:e.protocol,url:t,tokenEndpoint:n,deltaMode:uE[e.protocol]}}var fE={trailingSilenceMs:900,speechThreshold:.02,maxUtteranceMs:12e4};function pE(e,t,n,r=fE){if(e.kind!==`listening`&&e.kind!==`speaking`&&e.kind!==`trailing`)return e;if(n>=r.maxUtteranceMs)return e.kind===`listening`?{kind:`idle`}:{kind:`transcribing`};let i=t.level>=r.speechThreshold;if(e.kind===`listening`)return i?{kind:`speaking`}:e;if(e.kind===`speaking`)return i?e:{kind:`trailing`,silenceMs:t.elapsedMs};if(i)return{kind:`speaking`};let a=e.silenceMs+t.elapsedMs;return a>=r.trailingSilenceMs?{kind:`transcribing`}:{kind:`trailing`,silenceMs:a}}function mE(e){switch(e.kind){case`idle`:case`denied`:case`error`:return{kind:`listening`};case`listening`:return{kind:`idle`};case`speaking`:case`trailing`:return{kind:`transcribing`};case`transcribing`:case`unavailable`:return e}}function hE(e){return e.kind===`listening`||e.kind===`speaking`||e.kind===`trailing`}function gE(e,t){switch(e.kind){case`idle`:return t?.streaming===!0?`Dictate live`:`Dictate`;case`listening`:return`Listening…`;case`speaking`:return`Listening…`;case`trailing`:return`Listening…`;case`transcribing`:return`Transcribing…`;case`denied`:return`Microphone permission denied`;case`unavailable`:return e.reason;case`error`:return e.message}}var _E=class{constructor(e,t){this.deps=e,this.callbacks=t,this.state={kind:`idle`},this.elapsedMs=0}getState(){return this.state}async toggle(e){if(!aE(e)){this.setState({kind:`unavailable`,reason:`Dictation is not configured.`});return}let t=mE(this.state);if(t.kind===`listening`&&!hE(this.state)){await this.startListening(e);return}if(t.kind===`idle`){this.deps.recorder.cancel(),this.setState({kind:`idle`});return}if(t.kind===`transcribing`){await this.finish(e);return}this.setState(t)}async startListening(e){this.activeConfig=e,this.elapsedMs=0,this.setState({kind:`listening`});try{await this.deps.recorder.start((e,t)=>{this.onFrame(e,t)})}catch(e){this.setState(vE(e)?{kind:`denied`}:{kind:`error`,message:`Microphone unavailable: ${yE(e)}`})}}onFrame(e,t){if(!hE(this.state))return;this.elapsedMs+=t;let n=pE(this.state,{level:e,elapsedMs:t},this.elapsedMs,this.deps.captureConfig??fE);if(n!==this.state){if(n.kind===`transcribing`){this.finish(this.activeConfig);return}n.kind===`idle`&&this.deps.recorder.cancel(),this.setState(n)}}async finish(e){this.setState({kind:`transcribing`});let t;try{t=await this.deps.recorder.stop()}catch(e){this.setState({kind:`error`,message:`Recording failed: ${yE(e)}`});return}if(!aE(e)){this.setState({kind:`unavailable`,reason:`Dictation is not configured.`});return}let n=await(this.deps.transcribe??oE)(t,e,{fetch:this.deps.fetch??globalThis.fetch});if(!n.ok){this.setState({kind:`error`,message:n.message});return}this.callbacks.onTranscript(n.text),this.setState({kind:`idle`})}setState(e){this.state=e,this.callbacks.onState(e)}};function vE(e){if(typeof e!=`object`||!e)return!1;let t=`name`in e?e.name:void 0;return t===`NotAllowedError`||t===`SecurityError`}function yE(e){return e instanceof Error?e.message:String(e)}function bE(){return Ye`
3457
3479
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3458
3480
  <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>
3459
3481
  </svg>
3460
- `}function bE(){return Ye`
3482
+ `}function xE(){return Ye`
3461
3483
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3462
3484
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
3463
3485
  <path d="M21 3 11.5 12.5"></path>
3464
3486
  </svg>
3465
- `}function xE(){return Ye`
3487
+ `}function SE(){return Ye`
3466
3488
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3467
3489
  <path d="M4 7h11"></path>
3468
3490
  <path d="M4 12h7"></path>
3469
3491
  <path d="M4 17h7"></path>
3470
3492
  <path d="m15 14 5 3-5 3z"></path>
3471
3493
  </svg>
3472
- `}function SE(){return bE()}function CE(){return Ye`
3494
+ `}function CE(){return xE()}function wE(){return Ye`
3473
3495
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3474
3496
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
3475
3497
  </svg>
3476
- `}function wE(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return Ye`
3498
+ `}function TE(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return Ye`
3477
3499
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3478
3500
  ${Array.from({length:t},(i,a)=>{let o=3+a*(r+n),s=4+(a+1)/t*12,c=20-s;return Ye`<rect class=${a<e.filled?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${o} y=${c} width=${r} height=${s} rx="1"></rect>`})}
3479
3501
  </svg>
3480
- `}var TE=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function EE(e){return e===void 0||e===``?`off`:e}function DE(e,t){let n=t.length>=2?t:TE,r=n.length-1,i=EE(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var OE=fg(class extends pg{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===dg.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){}}),kE=class extends v{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
3502
+ `}var EE=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function DE(e){return e===void 0||e===``?`off`:e}function OE(e,t){let n=t.length>=2?t:EE,r=n.length-1,i=DE(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var kE=fg(class extends pg{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===dg.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){}}),AE=class extends v{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
3481
3503
  <div class="menu">
3482
3504
  ${this.items.map((e,t)=>g`
3483
- <button class=${t===this.selectedIndex?`selected`:``} ${OE(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
3505
+ <button class=${t===this.selectedIndex?`selected`:``} ${kE(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
3484
3506
  <strong>${e.insertText}</strong>
3485
3507
  <span>${e.detail}</span>
3486
3508
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
3487
3509
  </button>
3488
3510
  `)}
3489
3511
  </div>
3490
- `:null}static{this.styles=cg}};H([b({attribute:!1})],kE.prototype,`items`,void 0),H([b({type:Number})],kE.prototype,`selectedIndex`,void 0),H([b({attribute:!1})],kE.prototype,`onPick`,void 0),kE=H([y(`autocomplete-menu`)],kE);var q=class extends v{constructor(...e){super(...e),this.disabled=!1,this.machineId=`local`,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.collapsed=!1,this.availableThinkingLevels=[],this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.voiceState={kind:`idle`},this.attachments=[],this.attachmentError=void 0,this.attachingCount=0,this.attachingSettled=Promise.resolve(),this.attachmentSeq=0,this.requestVersion=0,this.historyDraftBeforeBrowse=``,this.editableCompartment=new i,this.readOnlyCompartment=new i,this.mobilePromptEnterMedia=qT(),this.explicitShiftKeyActive=!1,this.pendingPrompts=[],this.openAttachmentZoom=(e,t)=>{this.zoomedAttachment={src:e,alt:t}},this.closeAttachmentZoom=()=>{this.zoomedAttachment=void 0},this.onAttachmentZoomDialogClick=e=>{e.target===this.attachmentZoomDialog&&this.closeAttachmentZoom()},this.flushPendingPrompts=()=>{if(!navigator.onLine)return;let e=Js(this.machineId,this.sessionId??``);if(e===``)return;let t=xd(e);if(t.length===0)return;let n=t;(async()=>{let t=[],r=!1;for(let e of n)try{await this.onSend?.(e.text,e.behavior,e.attachments,e.attachments===void 0?void 0:this.effectiveAttachmentDelivery(),e.clientMessageId===void 0?void 0:{clientMessageId:e.clientMessageId})===!1&&t.push(e)}catch(n){r||=yd(n),t.push(e)}t.length===0?Cd(e):r||Cd(e),this.pendingPrompts=t.length===0?[]:t,n=t})()}}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=jE(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&jl(n,this.draft);let r=jE(this.machineId,this.sessionId);this.draft=r===void 0?``:Al(r),this.currentInputMode=Bd(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!AE(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor(),this.pendingPrompts=this.pendingPromptsForSession(),window.addEventListener(`online`,this.flushPendingPrompts)}connectedCallback(){super.connectedCallback(),this.pendingPrompts=this.pendingPromptsForSession()}updated(e){e.has(`collapsed`)&&(this.collapsed?(this.editor?.destroy(),this.editor=void 0):this.createEditor()),e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc(),this.syncAttachmentZoomDialog()}disconnectedCallback(){window.removeEventListener(`online`,this.flushPendingPrompts),this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){if(this.collapsed)return this.renderCollapsed();let e=this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.disabled||this.sending;return g`
3512
+ `:null}static{this.styles=cg}};H([b({attribute:!1})],AE.prototype,`items`,void 0),H([b({type:Number})],AE.prototype,`selectedIndex`,void 0),H([b({attribute:!1})],AE.prototype,`onPick`,void 0),AE=H([y(`autocomplete-menu`)],AE);var q=class extends v{constructor(...e){super(...e),this.disabled=!1,this.machineId=`local`,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.collapsed=!1,this.availableThinkingLevels=[],this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.voiceState={kind:`idle`},this.attachments=[],this.attachmentError=void 0,this.attachingCount=0,this.attachingSettled=Promise.resolve(),this.attachmentSeq=0,this.requestVersion=0,this.historyDraftBeforeBrowse=``,this.editableCompartment=new i,this.readOnlyCompartment=new i,this.mobilePromptEnterMedia=JT(),this.explicitShiftKeyActive=!1,this.pendingPrompts=[],this.openAttachmentZoom=(e,t)=>{this.zoomedAttachment={src:e,alt:t}},this.closeAttachmentZoom=()=>{this.zoomedAttachment=void 0},this.onAttachmentZoomDialogClick=e=>{e.target===this.attachmentZoomDialog&&this.closeAttachmentZoom()},this.flushPendingPrompts=()=>{if(!navigator.onLine)return;let e=Js(this.machineId,this.sessionId??``);if(e===``)return;let t=xd(e);if(t.length===0)return;let n=t;(async()=>{let t=[],r=!1;for(let e of n)try{await this.onSend?.(e.text,e.behavior,e.attachments,e.attachments===void 0?void 0:this.effectiveAttachmentDelivery(),e.clientMessageId===void 0?void 0:{clientMessageId:e.clientMessageId})===!1&&t.push(e)}catch(n){r||=yd(n),t.push(e)}t.length===0?Cd(e):r||Cd(e),this.pendingPrompts=t.length===0?[]:t,n=t})()}}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=ME(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&jl(n,this.draft);let r=ME(this.machineId,this.sessionId);this.draft=r===void 0?``:Al(r),this.currentInputMode=Bd(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!jE(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor(),this.pendingPrompts=this.pendingPromptsForSession(),window.addEventListener(`online`,this.flushPendingPrompts)}connectedCallback(){super.connectedCallback(),this.pendingPrompts=this.pendingPromptsForSession()}updated(e){e.has(`collapsed`)&&(this.collapsed?(this.editor?.destroy(),this.editor=void 0):this.createEditor()),e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc(),this.syncAttachmentZoomDialog()}disconnectedCallback(){window.removeEventListener(`online`,this.flushPendingPrompts),this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){if(this.collapsed)return this.renderCollapsed();let e=this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.disabled||this.sending;return g`
3491
3513
  <footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
3492
3514
  <input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
3493
3515
  ${this.renderAttachments()}
@@ -3495,14 +3517,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3495
3517
  ${t?g`<div class="mode-hint">Shell command${e.excludeFromContext?` · excluded from context`:``}</div>`:null}
3496
3518
  ${this.isCompacting&&!t?g`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
3497
3519
  <div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="Message pi" aria-disabled=${this.disabled?`true`:`false`}></div>
3498
- <button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${yE()}</button>
3520
+ <button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${bE()}</button>
3499
3521
  ${this.renderDictateButton(r)}
3500
3522
  <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${e=>{this.pick(e)}}></autocomplete-menu>
3501
3523
  </div>
3502
3524
  <div class="actions">
3503
3525
  ${this.renderCompactStatus()}
3504
- <button class="icon-button send-button" ?disabled=${r} title=${n?`Steer — joins the current turn at the next safe point`:`Send message`} aria-label=${n?`Steer current response (queued if busy)`:`Send message`} @click=${()=>{this.send(this.canSteer?`steer`:`followUp`)}}>${this.canSteer?SE():n?xE():bE()}</button>
3505
- <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?.()}>${CE()}</button>
3526
+ <button class="icon-button send-button" ?disabled=${r} title=${n?`Steer — joins the current turn at the next safe point`:`Send message`} aria-label=${n?`Steer current response (queued if busy)`:`Send message`} @click=${()=>{this.send(this.canSteer?`steer`:`followUp`)}}>${this.canSteer?CE():n?SE():xE()}</button>
3527
+ <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?.()}>${wE()}</button>
3506
3528
  </div>
3507
3529
  </footer>
3508
3530
  ${this.renderAttachmentZoom()}
@@ -3520,22 +3542,22 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3520
3542
  ${this.draftPreview===``?null:g`<span class="expand-composer-draft" dir="auto">${this.draftPreview}</span>`}
3521
3543
  </button>
3522
3544
  </footer>
3523
- `}get draftPreview(){let e=(this.editor?.state.doc.toString()??this.draft).trim().replace(/\s+/gu,` `);return e.length>60?`${e.slice(0,59)}…`:e}focusInput(){this.editor?.focus()}restorePrompt(e){this.attachmentError=void 0,this.attachments=e.attachments.filter(e=>e.kind===`image`).map((e,t)=>(this.attachmentSeq+=1,{id:`restored-${String(this.attachmentSeq)}`,kind:`image`,name:e.name??`image-${String(t+1)}`,mimeType:e.mimeType,data:e.data,size:Math.floor(e.data.length*3/4)})),this.replaceText(e.text),this.focusInput()}replaceText(t){this.draft=t;let n=jE(this.machineId,this.sessionId);n!==void 0&&jl(n,t);let r=this.editor;if(r!==void 0){let n=r.state.doc.toString();r.dispatch({...n===t?{}:{changes:{from:0,to:n.length,insert:t}},selection:e.cursor(t.length)})}this.requestVersion+=1,this.currentInputMode=Bd(t),this.completions=[],this.selectedIndex=0}get view(){return this.editor}renderCompactStatus(){let e=this.status;if(e===void 0)return null;let t=e.model?.id??`no model`,n=e.model?.provider!==void 0&&e.model.provider!==``?`${e.model.provider}/`:``;return g`
3545
+ `}get draftPreview(){let e=(this.editor?.state.doc.toString()??this.draft).trim().replace(/\s+/gu,` `);return e.length>60?`${e.slice(0,59)}…`:e}focusInput(){this.editor?.focus()}restorePrompt(e){this.attachmentError=void 0,this.attachments=e.attachments.filter(e=>e.kind===`image`).map((e,t)=>(this.attachmentSeq+=1,{id:`restored-${String(this.attachmentSeq)}`,kind:`image`,name:e.name??`image-${String(t+1)}`,mimeType:e.mimeType,data:e.data,size:Math.floor(e.data.length*3/4)})),this.replaceText(e.text),this.focusInput()}replaceText(t){this.draft=t;let n=ME(this.machineId,this.sessionId);n!==void 0&&jl(n,t);let r=this.editor;if(r!==void 0){let n=r.state.doc.toString();r.dispatch({...n===t?{}:{changes:{from:0,to:n.length,insert:t}},selection:e.cursor(t.length)})}this.requestVersion+=1,this.currentInputMode=Bd(t),this.completions=[],this.selectedIndex=0}get view(){return this.editor}renderCompactStatus(){let e=this.status;if(e===void 0)return null;let t=e.model?.id??`no model`,n=e.model?.provider!==void 0&&e.model.provider!==``?`${e.model.provider}/`:``;return g`
3524
3546
  <div class="compact-status" aria-label="Session status">
3525
3547
  <button class="select-model" title=${`Select model: ${n}${t}`} @click=${()=>this.onSelectModel?.()}>${n===``?null:g`<span class="select-model-provider">${n}</span>`}<span class="select-model-id">${t}</span></button>
3526
- <button class="select-thinking icon-button" title=${`Thinking level: ${EE(e.thinkingLevel)}`} aria-label=${`Thinking level: ${EE(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${wE(DE(e.thinkingLevel,this.availableThinkingLevels))}</button>
3548
+ <button class="select-thinking icon-button" title=${`Thinking level: ${DE(e.thinkingLevel)}`} aria-label=${`Thinking level: ${DE(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${TE(OE(e.thinkingLevel,this.availableThinkingLevels))}</button>
3527
3549
  </div>
3528
3550
  `}renderAttachments(){return this.attachments.length===0&&this.attachmentError===void 0?null:g`
3529
3551
  <div class="attachments" aria-label="Pending attachments">
3530
3552
  ${this.attachments.map(e=>g`
3531
- <div class=${`attachment-chip ${AT(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
3553
+ <div class=${`attachment-chip ${jT(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
3532
3554
  ${this.renderAttachmentPreview(e)}
3533
3555
  <button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
3534
3556
  </div>
3535
3557
  `)}
3536
3558
  ${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
3537
3559
  </div>
3538
- `}renderAttachmentPreview(e){if(AT(e)){let t=`data:${e.mimeType};base64,${e.data}`;return g`<img
3560
+ `}renderAttachmentPreview(e){if(jT(e)){let t=`data:${e.mimeType};base64,${e.data}`;return g`<img
3539
3561
  src=${t}
3540
3562
  alt=${e.name}
3541
3563
  role="button"
@@ -3544,7 +3566,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3544
3566
  @click=${()=>{this.openAttachmentZoom(t,e.name)}}
3545
3567
  @keydown=${n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),this.openAttachmentZoom(t,e.name))}}
3546
3568
  />`}return g`
3547
- <div class="attachment-file-preview" aria-hidden="true">${RE(e.name)}</div>
3569
+ <div class="attachment-file-preview" aria-hidden="true">${zE(e.name)}</div>
3548
3570
  <span class="attachment-file-name">${e.name}</span>
3549
3571
  `}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}syncAttachmentZoomDialog(){let e=this.attachmentZoomDialog;if(e!==void 0){if(this.zoomedAttachment!==void 0){try{e.open||e.showModal()}catch{this.zoomedAttachment=void 0;return}(this.renderRoot.querySelector(`.attachment-zoom-close`)??e).focus();return}e.open&&e.close()}}renderAttachmentZoom(){let e=this.zoomedAttachment;return g`
3550
3572
  <dialog class="attachment-zoom" @click=${this.onAttachmentZoomDialogClick} @close=${this.closeAttachmentZoom} @cancel=${this.closeAttachmentZoom}>
@@ -3553,7 +3575,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3553
3575
  <img class="attachment-zoom-full" src=${e.src} alt=${e.alt} />
3554
3576
  `}
3555
3577
  </dialog>
3556
- `}async handlePaste(e){let t=FE(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&IE(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=FE(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,this.attachingCount+=1;let t=kT(e,zE);this.attachingSettled=this.attachingSettled.then(async()=>{await t}).catch(()=>void 0);let n;try{n=await t}finally{--this.attachingCount}let{attachments:r,error:i}=n;r.length>0&&(this.attachments=[...this.attachments,...r.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>LE(e))}renderDictateButton(e){if(!iE(this.speechToText))return null;let t=uE(this.speechToText.streaming).kind!==`unavailable`,n=hE(this.voiceState,{streaming:t}),r=mE(this.voiceState);return g`
3578
+ `}async handlePaste(e){let t=IE(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&LE(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=IE(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,this.attachingCount+=1;let t=AT(e,BE);this.attachingSettled=this.attachingSettled.then(async()=>{await t}).catch(()=>void 0);let n;try{n=await t}finally{--this.attachingCount}let{attachments:r,error:i}=n;r.length>0&&(this.attachments=[...this.attachments,...r.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>RE(e))}renderDictateButton(e){if(!aE(this.speechToText))return null;let t=dE(this.speechToText.streaming).kind!==`unavailable`,n=gE(this.voiceState,{streaming:t}),r=hE(this.voiceState);return g`
3557
3579
  <button
3558
3580
  class=${`editor-dictate icon-button${r?` listening`:``}`}
3559
3581
  type="button"
@@ -3563,8 +3585,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3563
3585
  aria-pressed=${String(r)}
3564
3586
  @click=${()=>{this.toggleDictation()}}
3565
3587
  >${r?`■`:`●`}</button>
3566
- `}async toggleDictation(){this.voice??=new gE({recorder:nE()},{onState:e=>{this.voiceState=e},onTranscript:e=>{this.insertDictatedText(e)}}),await this.voice.toggle(this.speechToText)}insertDictatedText(e){let t=this.editor?.state.doc.toString()??this.draft,n=t===``||t.endsWith(` `)||t.endsWith(`
3567
- `)?``:` `;this.replaceText(`${t}${n}${e}`)}effectiveAttachmentDelivery(){return MT(`inline`,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new m({parent:this.editorHost,state:l.create({doc:this.draft,extensions:[ee(),re(),t(),d.of(` `),r(a,{fallback:!0}),m.lineWrapping,n(),m.contentAttributes.of(e=>HE(e.state.sliceDoc(0,e.state.selection.main.head))),m.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),s(UE()),this.editableCompartment.of(m.editable.of(!this.disabled)),this.readOnlyCompartment.of(l.readOnly.of(this.disabled)),m.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),o.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:e=>this.handleEditorArrow(e,`newer`)},{key:`ArrowUp`,run:e=>this.handleEditorArrow(e,`older`)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>u.shift?.(e)??!1},{key:`Backspace`,run:e=>te(e)},...c,...f])]})}))}syncEditorDoc(){let t=this.editor;if(!t)return;let n=t.state.doc.toString();n!==this.draft&&t.dispatch({changes:{from:0,to:n.length,insert:this.draft},selection:e.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(m.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(l.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=jE(this.machineId,this.sessionId);t!==void 0&&jl(t,this.draft);let n=Bd(this.draft);Hd(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 I.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(ME);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.projectId!==void 0&&this.workspaceId!==void 0){let n=await I.files(e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId}).catch(NE);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=Fd(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}:{}}})}else if(e.kind===`model`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await I.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(PE);if(t!==this.requestVersion)return;this.completions=Md(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return Ad(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}handleEditorArrow(e,t){return this.completions.length?this.moveCompletion(t===`older`?-1:1):this.browsePromptHistory(e,WT(t))}browsePromptHistory(e,t){let n=jE(this.machineId,this.sessionId);if(n===void 0)return!1;let r=zT(n);if(r.length===0)return!1;let i=e.state.selection.main.head,a=e.state.selection.main.empty,o=e.state.doc.toString();if(this.historyIndex===void 0){if(!(a&&i===o.length&&o.trim()===``))return!1;this.historyDraftBeforeBrowse=o,this.historyIndex=0}else{let e=this.historyIndex+t;if(e<0)return!0;if(e>=r.length)return this.historyIndex=void 0,this.replaceText(this.historyDraftBeforeBrowse),!0;this.historyIndex=e}let s=r[this.historyIndex]??this.historyDraftBeforeBrowse;return this.replaceText(s),!0}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`r`)return e.preventDefault(),this.openPromptHistoryPicker();if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,e.key!==`ArrowUp`&&e.key!==`ArrowDown`&&(this.historyIndex=void 0),!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=QT(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 $T(t,this.mobilePromptEnterMedia,YT())?(this.send(this.canSteer?`steer`:`followUp`),!0):ne(e)||p(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):u.run?.(e)??!1}pick(t){let n=this.editor;if(!n)return;if(t.kind===`history`){this.historyIndex=void 0,this.replaceText(t.insertText),this.completions=[];return}let r=t.kind===`file`&&(t.insertText.endsWith(`/`)||t.cursorOffset!==void 0)?``:` `,i=t.replaceFrom+(t.cursorOffset??t.insertText.length)+r.length,a=t.insertText.endsWith(`"`)&&this.draft.slice(t.replaceTo).startsWith(`"`)?t.replaceTo+1:t.replaceTo;n.dispatch({changes:{from:t.replaceFrom,to:a,insert:`${t.insertText}${r}`},selection:e.cursor(i),scrollIntoView:!0}),this.completions=[]}openPromptHistoryPicker(){let e=jE(this.machineId,this.sessionId);if(e===void 0)return!1;let t=HT(e,this.draft).slice(0,12);return t.length===0?!1:(this.selectedIndex=0,this.completions=t.map(e=>({kind:`history`,replaceFrom:0,replaceTo:this.draft.length,insertText:e,detail:`history`,description:e})),!0)}pendingPromptsForSession(){let e=Js(this.machineId,this.sessionId??``);return e===``?[]:xd(e)}send(e){if(this.disabled||this.sending)return;if(this.attachingCount>0){this.attachingSettled.then(()=>{this.send(e)});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(),o=jE(this.machineId,this.sessionId);o!==void 0&&t!==``&&VT(o,t);let s={text:this.draft,attachments:n};this.resetComposer(),this.deliverAndRestoreOnFailure(t,r,i,a,s)}async deliverAndRestoreOnFailure(e,t,n,r,i){let a,o;try{a=await this.onSend?.(e,t,n,n===void 0?void 0:r)}catch(e){a=!1,o=e}if(a===!1){if(yd(o)){let r=Js(this.machineId,this.sessionId??``);if(r!==``){let i=o instanceof bd?o.clientMessageId:void 0;Sd(r,{text:e,...t===void 0?{}:{behavior:t},...i===void 0?{}:{clientMessageId:i},...n===void 0||n.length===0?{}:{attachments:n},at:new Date().toISOString()}),this.pendingPrompts=xd(r);return}}(this.editor?.state.doc.toString()??this.draft).trim()===``&&(this.attachments=i.attachments,this.replaceText(i.text))}}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=jE(this.machineId,this.sessionId);e!==void 0&&Ml(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=lg}};H([b({type:Boolean})],q.prototype,`disabled`,void 0),H([b()],q.prototype,`sessionId`,void 0),H([b()],q.prototype,`cwd`,void 0),H([b()],q.prototype,`machineId`,void 0),H([b()],q.prototype,`projectId`,void 0),H([b()],q.prototype,`workspaceId`,void 0),H([b({type:Boolean})],q.prototype,`canSteer`,void 0),H([b({type:Boolean})],q.prototype,`isCompacting`,void 0),H([b({type:Boolean})],q.prototype,`canStop`,void 0),H([b({attribute:!1})],q.prototype,`status`,void 0),H([b({type:Boolean})],q.prototype,`sending`,void 0),H([b({type:Boolean,reflect:!0})],q.prototype,`collapsed`,void 0),H([b({attribute:!1})],q.prototype,`onSend`,void 0),H([b({attribute:!1})],q.prototype,`onStop`,void 0),H([b({attribute:!1})],q.prototype,`onSelectModel`,void 0),H([b({attribute:!1})],q.prototype,`onSelectThinking`,void 0),H([b({attribute:!1})],q.prototype,`onExpand`,void 0),H([b({attribute:!1})],q.prototype,`availableThinkingLevels`,void 0),H([S(`.markdown-editor`)],q.prototype,`editorHost`,void 0),H([S(`.attachment-input`)],q.prototype,`attachmentInput`,void 0),H([S(`dialog.attachment-zoom`)],q.prototype,`attachmentZoomDialog`,void 0),H([x()],q.prototype,`currentInputMode`,void 0),H([x()],q.prototype,`completions`,void 0),H([x()],q.prototype,`selectedIndex`,void 0),H([b({attribute:!1})],q.prototype,`speechToText`,void 0),H([x()],q.prototype,`voiceState`,void 0),H([x()],q.prototype,`zoomedAttachment`,void 0),H([x()],q.prototype,`attachments`,void 0),H([x()],q.prototype,`attachmentError`,void 0),H([x()],q.prototype,`attachingCount`,void 0),H([x()],q.prototype,`pendingPrompts`,void 0),q=H([y(`prompt-editor`)],q);function AE(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 jE(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Js(e,t)}function ME(){return[]}function NE(){return[]}function PE(){return[]}function FE(e){return e===null?[]:Array.from(e.files)}function IE(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function LE(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 RE(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function zE(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 BE={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},VE={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function HE(e){return Bd(e).kind===`normal`?BE:VE}function UE(){let e=document.createElement(`span`);e.className=`composer-placeholder`;let t=document.createElement(`span`);t.className=`composer-placeholder-label`,t.textContent=`Message pi…`;let n=document.createElement(`span`);return n.className=`composer-placeholder-hints`,n.textContent=`/ @ #`,e.append(t,n),e}function WE(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`}}var GE=class extends v{constructor(...e){super(...e),this.warningCount=0,this.warningsExpanded=!1,this.handleToggleWarnings=()=>{this.onToggleWarnings?.()}}render(){let e=this.status;if(e===void 0)return g`<div class="bar muted">No session status yet</div>`;let t=e.contextUsage,n=t?t.percent==null?`context ${Mh(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Mh(t.contextWindow)}`:`context unknown`,r=e.tokens,i=WE(this.warningCount,this.warningsExpanded);return g`
3588
+ `}async toggleDictation(){this.voice??=new _E({recorder:rE()},{onState:e=>{this.voiceState=e},onTranscript:e=>{this.insertDictatedText(e)}}),await this.voice.toggle(this.speechToText)}insertDictatedText(e){let t=this.editor?.state.doc.toString()??this.draft,n=t===``||t.endsWith(` `)||t.endsWith(`
3589
+ `)?``:` `;this.replaceText(`${t}${n}${e}`)}effectiveAttachmentDelivery(){return NT(`inline`,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new m({parent:this.editorHost,state:l.create({doc:this.draft,extensions:[ee(),re(),t(),d.of(` `),r(a,{fallback:!0}),m.lineWrapping,n(),m.contentAttributes.of(e=>UE(e.state.sliceDoc(0,e.state.selection.main.head))),m.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),s(WE()),this.editableCompartment.of(m.editable.of(!this.disabled)),this.readOnlyCompartment.of(l.readOnly.of(this.disabled)),m.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),o.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:e=>this.handleEditorArrow(e,`newer`)},{key:`ArrowUp`,run:e=>this.handleEditorArrow(e,`older`)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>u.shift?.(e)??!1},{key:`Backspace`,run:e=>te(e)},...c,...f])]})}))}syncEditorDoc(){let t=this.editor;if(!t)return;let n=t.state.doc.toString();n!==this.draft&&t.dispatch({changes:{from:0,to:n.length,insert:this.draft},selection:e.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(m.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(l.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=ME(this.machineId,this.sessionId);t!==void 0&&jl(t,this.draft);let n=Bd(this.draft);Hd(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 I.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(NE);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.projectId!==void 0&&this.workspaceId!==void 0){let n=await I.files(e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId}).catch(PE);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=Fd(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}:{}}})}else if(e.kind===`model`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await I.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(FE);if(t!==this.requestVersion)return;this.completions=Md(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return Ad(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}handleEditorArrow(e,t){return this.completions.length?this.moveCompletion(t===`older`?-1:1):this.browsePromptHistory(e,GT(t))}browsePromptHistory(e,t){let n=ME(this.machineId,this.sessionId);if(n===void 0)return!1;let r=BT(n);if(r.length===0)return!1;let i=e.state.selection.main.head,a=e.state.selection.main.empty,o=e.state.doc.toString();if(this.historyIndex===void 0){if(!(a&&i===o.length&&o.trim()===``))return!1;this.historyDraftBeforeBrowse=o,this.historyIndex=0}else{let e=this.historyIndex+t;if(e<0)return!0;if(e>=r.length)return this.historyIndex=void 0,this.replaceText(this.historyDraftBeforeBrowse),!0;this.historyIndex=e}let s=r[this.historyIndex]??this.historyDraftBeforeBrowse;return this.replaceText(s),!0}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`r`)return e.preventDefault(),this.openPromptHistoryPicker();if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,e.key!==`ArrowUp`&&e.key!==`ArrowDown`&&(this.historyIndex=void 0),!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=$T(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 eE(t,this.mobilePromptEnterMedia,XT())?(this.send(this.canSteer?`steer`:`followUp`),!0):ne(e)||p(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):u.run?.(e)??!1}pick(t){let n=this.editor;if(!n)return;if(t.kind===`history`){this.historyIndex=void 0,this.replaceText(t.insertText),this.completions=[];return}let r=t.kind===`file`&&(t.insertText.endsWith(`/`)||t.cursorOffset!==void 0)?``:` `,i=t.replaceFrom+(t.cursorOffset??t.insertText.length)+r.length,a=t.insertText.endsWith(`"`)&&this.draft.slice(t.replaceTo).startsWith(`"`)?t.replaceTo+1:t.replaceTo;n.dispatch({changes:{from:t.replaceFrom,to:a,insert:`${t.insertText}${r}`},selection:e.cursor(i),scrollIntoView:!0}),this.completions=[]}openPromptHistoryPicker(){let e=ME(this.machineId,this.sessionId);if(e===void 0)return!1;let t=UT(e,this.draft).slice(0,12);return t.length===0?!1:(this.selectedIndex=0,this.completions=t.map(e=>({kind:`history`,replaceFrom:0,replaceTo:this.draft.length,insertText:e,detail:`history`,description:e})),!0)}pendingPromptsForSession(){let e=Js(this.machineId,this.sessionId??``);return e===``?[]:xd(e)}send(e){if(this.disabled||this.sending)return;if(this.attachingCount>0){this.attachingSettled.then(()=>{this.send(e)});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(),o=ME(this.machineId,this.sessionId);o!==void 0&&t!==``&&HT(o,t);let s={text:this.draft,attachments:n};this.resetComposer(),this.deliverAndRestoreOnFailure(t,r,i,a,s)}async deliverAndRestoreOnFailure(e,t,n,r,i){let a,o;try{a=await this.onSend?.(e,t,n,n===void 0?void 0:r)}catch(e){a=!1,o=e}if(a===!1){if(yd(o)){let r=Js(this.machineId,this.sessionId??``);if(r!==``){let i=o instanceof bd?o.clientMessageId:void 0;Sd(r,{text:e,...t===void 0?{}:{behavior:t},...i===void 0?{}:{clientMessageId:i},...n===void 0||n.length===0?{}:{attachments:n},at:new Date().toISOString()}),this.pendingPrompts=xd(r);return}}(this.editor?.state.doc.toString()??this.draft).trim()===``&&(this.attachments=i.attachments,this.replaceText(i.text))}}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=ME(this.machineId,this.sessionId);e!==void 0&&Ml(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=lg}};H([b({type:Boolean})],q.prototype,`disabled`,void 0),H([b()],q.prototype,`sessionId`,void 0),H([b()],q.prototype,`cwd`,void 0),H([b()],q.prototype,`machineId`,void 0),H([b()],q.prototype,`projectId`,void 0),H([b()],q.prototype,`workspaceId`,void 0),H([b({type:Boolean})],q.prototype,`canSteer`,void 0),H([b({type:Boolean})],q.prototype,`isCompacting`,void 0),H([b({type:Boolean})],q.prototype,`canStop`,void 0),H([b({attribute:!1})],q.prototype,`status`,void 0),H([b({type:Boolean})],q.prototype,`sending`,void 0),H([b({type:Boolean,reflect:!0})],q.prototype,`collapsed`,void 0),H([b({attribute:!1})],q.prototype,`onSend`,void 0),H([b({attribute:!1})],q.prototype,`onStop`,void 0),H([b({attribute:!1})],q.prototype,`onSelectModel`,void 0),H([b({attribute:!1})],q.prototype,`onSelectThinking`,void 0),H([b({attribute:!1})],q.prototype,`onExpand`,void 0),H([b({attribute:!1})],q.prototype,`availableThinkingLevels`,void 0),H([S(`.markdown-editor`)],q.prototype,`editorHost`,void 0),H([S(`.attachment-input`)],q.prototype,`attachmentInput`,void 0),H([S(`dialog.attachment-zoom`)],q.prototype,`attachmentZoomDialog`,void 0),H([x()],q.prototype,`currentInputMode`,void 0),H([x()],q.prototype,`completions`,void 0),H([x()],q.prototype,`selectedIndex`,void 0),H([b({attribute:!1})],q.prototype,`speechToText`,void 0),H([x()],q.prototype,`voiceState`,void 0),H([x()],q.prototype,`zoomedAttachment`,void 0),H([x()],q.prototype,`attachments`,void 0),H([x()],q.prototype,`attachmentError`,void 0),H([x()],q.prototype,`attachingCount`,void 0),H([x()],q.prototype,`pendingPrompts`,void 0),q=H([y(`prompt-editor`)],q);function jE(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 ME(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Js(e,t)}function NE(){return[]}function PE(){return[]}function FE(){return[]}function IE(e){return e===null?[]:Array.from(e.files)}function LE(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function RE(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 zE(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function BE(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 VE={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},HE={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function UE(e){return Bd(e).kind===`normal`?VE:HE}function WE(){let e=document.createElement(`span`);e.className=`composer-placeholder`;let t=document.createElement(`span`);t.className=`composer-placeholder-label`,t.textContent=`Message pi…`;let n=document.createElement(`span`);return n.className=`composer-placeholder-hints`,n.textContent=`/ @ #`,e.append(t,n),e}function GE(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`}}var KE=class extends v{constructor(...e){super(...e),this.warningCount=0,this.warningsExpanded=!1,this.handleToggleWarnings=()=>{this.onToggleWarnings?.()}}render(){let e=this.status;if(e===void 0)return g`<div class="bar muted">No session status yet</div>`;let t=e.contextUsage,n=t?t.percent==null?`context ${Mh(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Mh(t.contextWindow)}`:`context unknown`,r=e.tokens,i=GE(this.warningCount,this.warningsExpanded);return g`
3568
3590
  <div class="bar">
3569
3591
  ${i===void 0||this.onToggleWarnings===void 0?null:g`
3570
3592
  <button
@@ -3585,7 +3607,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3585
3607
  <span>${Fh(e.cost)}</span>
3586
3608
  ${e.pendingMessageCount>0?g`<span>${String(e.pendingMessageCount)} queued</span>`:null}
3587
3609
  </div>
3588
- `}static{this.styles=sg}};H([b({attribute:!1})],GE.prototype,`status`,void 0),H([b({type:Number})],GE.prototype,`warningCount`,void 0),H([b({type:Boolean})],GE.prototype,`warningsExpanded`,void 0),H([b({attribute:!1})],GE.prototype,`onToggleWarnings`,void 0),GE=H([y(`status-bar`)],GE);function KE(e){return e.composedPath().some(e=>e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement&&e.hasAttribute(`href`))}var qE=class extends v{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
3610
+ `}static{this.styles=sg}};H([b({attribute:!1})],KE.prototype,`status`,void 0),H([b({type:Number})],KE.prototype,`warningCount`,void 0),H([b({type:Boolean})],KE.prototype,`warningsExpanded`,void 0),H([b({attribute:!1})],KE.prototype,`onToggleWarnings`,void 0),KE=H([y(`status-bar`)],KE);function qE(e){return e.composedPath().some(e=>e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement&&e.hasAttribute(`href`))}var JE=class extends v{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
3589
3611
  <modal-surface
3590
3612
  .onClose=${()=>this.onCancel?.()}
3591
3613
  .initialFocus=${this.searchable?`input`:`.options`}
@@ -3602,7 +3624,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3602
3624
  <button
3603
3625
  class=${t===this.selectedIndex?`selected`:``}
3604
3626
  aria-current=${t===this.selectedIndex?`true`:_}
3605
- ${OE(t===this.selectedIndex,e.value)}
3627
+ ${kE(t===this.selectedIndex,e.value)}
3606
3628
  @focus=${()=>{this.selectedIndex=t}}
3607
3629
  @click=${()=>this.onPick?.(e.value)}
3608
3630
  >
@@ -3613,7 +3635,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3613
3635
  ${e.length===0?g`<div class="empty">No matching options</div>`:null}
3614
3636
  </div>
3615
3637
  </modal-surface>
3616
- `}firstUpdated(){this.selectInitialValue()}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(){return Ed(this.options,this.query,e=>`${e.label} ${e.description??``} ${e.value}`)}handleKeyDown(e){if(KE(e))return;let t=this.filteredOptions();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=h`
3638
+ `}firstUpdated(){this.selectInitialValue()}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(){return Ed(this.options,this.query,e=>`${e.label} ${e.description??``} ${e.value}`)}handleKeyDown(e){if(qE(e))return;let t=this.filteredOptions();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=h`
3617
3639
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
3618
3640
  modal-surface { --modal-surface-width: min(720px, calc(100vw - 40px)); --modal-surface-max-height: min(640px, calc(100vh - 40px)); }
3619
3641
  header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
@@ -3629,7 +3651,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3629
3651
  .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
3630
3652
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
3631
3653
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
3632
- `}};H([b()],qE.prototype,`title`,void 0),H([b({type:Boolean})],qE.prototype,`searchable`,void 0),H([b({attribute:!1})],qE.prototype,`options`,void 0),H([b({attribute:!1})],qE.prototype,`selectedValue`,void 0),H([b({attribute:!1})],qE.prototype,`onPick`,void 0),H([b({attribute:!1})],qE.prototype,`onCancel`,void 0),H([x()],qE.prototype,`selectedIndex`,void 0),H([x()],qE.prototype,`query`,void 0),qE=H([y(`command-picker`)],qE);function JE(e,t){let n=e.toLowerCase();return t.split(/\s+/).every(e=>n.includes(e))}function YE(e){return e.trim().toLowerCase()}function XE(e){return`${e.provider}/${e.id}`}function ZE(e,t){let n=YE(t);return n===``?[...e]:e.filter(e=>JE(`${e.label} ${e.description??``} ${e.value}`,n))}function QE(e,t){let n=YE(t),r=n===``?[...e]:e.filter(e=>JE(`${e.provider} ${e.id} ${e.name??``}`,n));return{rows:r,showGroupHeaders:n===``&&r.some(e=>e.enabled)&&r.some(e=>!e.enabled)}}var $E=class extends v{constructor(...e){super(...e),this.title=`Select Model`,this.options=[],this.catalog=[],this.mode=`enabled`,this.selectedIndex=0,this.query=``,this.pendingToggles=new Set}render(){let e=this.visibleRows();return g`
3654
+ `}};H([b()],JE.prototype,`title`,void 0),H([b({type:Boolean})],JE.prototype,`searchable`,void 0),H([b({attribute:!1})],JE.prototype,`options`,void 0),H([b({attribute:!1})],JE.prototype,`selectedValue`,void 0),H([b({attribute:!1})],JE.prototype,`onPick`,void 0),H([b({attribute:!1})],JE.prototype,`onCancel`,void 0),H([x()],JE.prototype,`selectedIndex`,void 0),H([x()],JE.prototype,`query`,void 0),JE=H([y(`command-picker`)],JE);function YE(e,t){let n=e.toLowerCase();return t.split(/\s+/).every(e=>n.includes(e))}function XE(e){return e.trim().toLowerCase()}function ZE(e){return`${e.provider}/${e.id}`}function QE(e,t){let n=XE(t);return n===``?[...e]:e.filter(e=>YE(`${e.label} ${e.description??``} ${e.value}`,n))}function $E(e,t){let n=XE(t),r=n===``?[...e]:e.filter(e=>YE(`${e.provider} ${e.id} ${e.name??``}`,n));return{rows:r,showGroupHeaders:n===``&&r.some(e=>e.enabled)&&r.some(e=>!e.enabled)}}var eD=class extends v{constructor(...e){super(...e),this.title=`Select Model`,this.options=[],this.catalog=[],this.mode=`enabled`,this.selectedIndex=0,this.query=``,this.pendingToggles=new Set}render(){let e=this.visibleRows();return g`
3633
3655
  <modal-surface
3634
3656
  .onClose=${()=>this.onCancel?.()}
3635
3657
  .initialFocus=${`input.search`}
@@ -3650,19 +3672,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3650
3672
  ${e.length===0?g`<div class="empty">No matching options</div>`:null}
3651
3673
  </div>
3652
3674
  </modal-surface>
3653
- `}firstUpdated(){this.anchorSelectionToSelectedValue()}willUpdate(e){if(!e.has(`catalog`)||this.mode!==`all`)return;let t=e.get(`catalog`);if(t===void 0)return;let n=QE(t,this.query).rows[this.selectedIndex],r=QE(this.catalog,this.query).rows,i=n===void 0?void 0:XE(n),a=i===void 0?-1:r.findIndex(e=>XE(e)===i);this.selectedIndex=a>=0?a:Math.min(this.selectedIndex,Math.max(r.length-1,0))}renderScopeToggleButton(e,t){return g`<button aria-pressed=${this.mode===e?`true`:`false`} @click=${()=>{this.selectMode(e)}}>${t}</button>`}renderEnabledList(){return ZE(this.options,this.query).map((e,t)=>g`
3675
+ `}firstUpdated(){this.anchorSelectionToSelectedValue()}willUpdate(e){if(!e.has(`catalog`)||this.mode!==`all`)return;let t=e.get(`catalog`);if(t===void 0)return;let n=$E(t,this.query).rows[this.selectedIndex],r=$E(this.catalog,this.query).rows,i=n===void 0?void 0:ZE(n),a=i===void 0?-1:r.findIndex(e=>ZE(e)===i);this.selectedIndex=a>=0?a:Math.min(this.selectedIndex,Math.max(r.length-1,0))}renderScopeToggleButton(e,t){return g`<button aria-pressed=${this.mode===e?`true`:`false`} @click=${()=>{this.selectMode(e)}}>${t}</button>`}renderEnabledList(){return QE(this.options,this.query).map((e,t)=>g`
3654
3676
  <button
3655
3677
  class=${t===this.selectedIndex?`selected`:``}
3656
3678
  aria-current=${t===this.selectedIndex?`true`:_}
3657
- ${OE(t===this.selectedIndex,e.value)}
3679
+ ${kE(t===this.selectedIndex,e.value)}
3658
3680
  @focus=${()=>{this.selectedIndex=t}}
3659
3681
  @click=${()=>this.onPick?.(e.value)}
3660
3682
  >
3661
3683
  <span>${e.label}</span>
3662
3684
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
3663
3685
  </button>
3664
- `)}renderCatalogList(){let e=QE(this.catalog,this.query),t=[],n;return e.rows.forEach((r,i)=>{e.showGroupHeaders&&r.enabled!==n&&t.push(g`<div class="group-header">${r.enabled?`Enabled`:`Other models`}</div>`),n=r.enabled,t.push(this.renderCatalogRow(r,i))}),t}renderCatalogRow(e,t){let n=XE(e),r=t===this.selectedIndex,i=this.pendingToggles.has(n);return g`
3665
- <div class="catalog-row ${r?`selected`:``}" ${OE(r,n)}>
3686
+ `)}renderCatalogList(){let e=$E(this.catalog,this.query),t=[],n;return e.rows.forEach((r,i)=>{e.showGroupHeaders&&r.enabled!==n&&t.push(g`<div class="group-header">${r.enabled?`Enabled`:`Other models`}</div>`),n=r.enabled,t.push(this.renderCatalogRow(r,i))}),t}renderCatalogRow(e,t){let n=ZE(e),r=t===this.selectedIndex,i=this.pendingToggles.has(n);return g`
3687
+ <div class="catalog-row ${r?`selected`:``}" ${kE(r,n)}>
3666
3688
  <input
3667
3689
  type="checkbox"
3668
3690
  .checked=${e.enabled}
@@ -3680,7 +3702,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3680
3702
  <small>${e.provider}</small>
3681
3703
  </button>
3682
3704
  </div>
3683
- `}visibleRows(){return this.mode===`all`?QE(this.catalog,this.query).rows.map(e=>({value:XE(e),entry:e})):ZE(this.options,this.query).map(e=>({value:e.value}))}anchorSelectionToSelectedValue(){if(this.selectedValue===void 0){this.selectedIndex=0;return}let e=this.visibleRows().findIndex(e=>e.value===this.selectedValue);this.selectedIndex=e>=0?e:0}selectMode(e){e!==this.mode&&(this.mode=e,this.anchorSelectionToSelectedValue())}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}handleKeyDown(e){if(KE(e))return;let t=this.visibleRows();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.onPick?.(n.value)}else if(e.key===` `&&this.mode===`all`){if(e.composedPath().some(e=>e instanceof HTMLInputElement))return;let n=t[this.selectedIndex];if(n?.entry===void 0)return;e.preventDefault(),this.requestEnabledToggle(n.entry)}}handleEnableToggleClick(e,t){t.preventDefault(),t.currentTarget instanceof HTMLInputElement&&(t.currentTarget.checked=e.enabled),this.requestEnabledToggle(e)}requestEnabledToggle(e){let t=XE(e);if(this.pendingToggles.has(t))return;let n=new Set(this.pendingToggles);n.add(t),this.pendingToggles=n,this.settleEnabledToggle(t,e)}async settleEnabledToggle(e,t){try{await this.onToggleEnabled?.(t.provider,t.id,!t.enabled)}catch(t){console.warn(`Failed to toggle model ${e}`,t)}finally{let t=new Set(this.pendingToggles);t.delete(e),this.pendingToggles=t}}static{this.styles=h`
3705
+ `}visibleRows(){return this.mode===`all`?$E(this.catalog,this.query).rows.map(e=>({value:ZE(e),entry:e})):QE(this.options,this.query).map(e=>({value:e.value}))}anchorSelectionToSelectedValue(){if(this.selectedValue===void 0){this.selectedIndex=0;return}let e=this.visibleRows().findIndex(e=>e.value===this.selectedValue);this.selectedIndex=e>=0?e:0}selectMode(e){e!==this.mode&&(this.mode=e,this.anchorSelectionToSelectedValue())}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}handleKeyDown(e){if(qE(e))return;let t=this.visibleRows();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.onPick?.(n.value)}else if(e.key===` `&&this.mode===`all`){if(e.composedPath().some(e=>e instanceof HTMLInputElement))return;let n=t[this.selectedIndex];if(n?.entry===void 0)return;e.preventDefault(),this.requestEnabledToggle(n.entry)}}handleEnableToggleClick(e,t){t.preventDefault(),t.currentTarget instanceof HTMLInputElement&&(t.currentTarget.checked=e.enabled),this.requestEnabledToggle(e)}requestEnabledToggle(e){let t=ZE(e);if(this.pendingToggles.has(t))return;let n=new Set(this.pendingToggles);n.add(t),this.pendingToggles=n,this.settleEnabledToggle(t,e)}async settleEnabledToggle(e,t){try{await this.onToggleEnabled?.(t.provider,t.id,!t.enabled)}catch(t){console.warn(`Failed to toggle model ${e}`,t)}finally{let t=new Set(this.pendingToggles);t.delete(e),this.pendingToggles=t}}static{this.styles=h`
3684
3706
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
3685
3707
  modal-surface { --modal-surface-width: min(720px, calc(100vw - 40px)); --modal-surface-max-height: min(640px, calc(100vh - 40px)); }
3686
3708
  header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
@@ -3701,7 +3723,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3701
3723
  .group-header { padding: 8px 12px 4px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
3702
3724
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
3703
3725
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
3704
- `}};H([b()],$E.prototype,`title`,void 0),H([b({attribute:!1})],$E.prototype,`options`,void 0),H([b({attribute:!1})],$E.prototype,`catalog`,void 0),H([b({attribute:!1})],$E.prototype,`selectedValue`,void 0),H([b({attribute:!1})],$E.prototype,`onPick`,void 0),H([b({attribute:!1})],$E.prototype,`onCancel`,void 0),H([b({attribute:!1})],$E.prototype,`onToggleEnabled`,void 0),H([x()],$E.prototype,`mode`,void 0),H([x()],$E.prototype,`selectedIndex`,void 0),H([x()],$E.prototype,`query`,void 0),H([x()],$E.prototype,`pendingToggles`,void 0),$E=H([y(`model-picker`)],$E);var eD=class extends v{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
3726
+ `}};H([b()],eD.prototype,`title`,void 0),H([b({attribute:!1})],eD.prototype,`options`,void 0),H([b({attribute:!1})],eD.prototype,`catalog`,void 0),H([b({attribute:!1})],eD.prototype,`selectedValue`,void 0),H([b({attribute:!1})],eD.prototype,`onPick`,void 0),H([b({attribute:!1})],eD.prototype,`onCancel`,void 0),H([b({attribute:!1})],eD.prototype,`onToggleEnabled`,void 0),H([x()],eD.prototype,`mode`,void 0),H([x()],eD.prototype,`selectedIndex`,void 0),H([x()],eD.prototype,`query`,void 0),H([x()],eD.prototype,`pendingToggles`,void 0),eD=H([y(`model-picker`)],eD);var tD=class extends v{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
3705
3727
  <modal-surface
3706
3728
  .onClose=${()=>this.onCancel?.()}
3707
3729
  .initialFocus=${`input`}
@@ -3723,7 +3745,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3723
3745
  ?disabled=${e.enabled===!1}
3724
3746
  title=${e.disabledReason??e.title}
3725
3747
  aria-current=${t===this.selectedIndex?`true`:_}
3726
- ${OE(t===this.selectedIndex,e.id)}
3748
+ ${kE(t===this.selectedIndex,e.id)}
3727
3749
  @focus=${()=>{this.selectedIndex=t}}
3728
3750
  @click=${()=>{this.run(e)}}
3729
3751
  >
@@ -3738,7 +3760,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3738
3760
  `)}
3739
3761
  </div>
3740
3762
  </modal-surface>
3741
- `}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 tD(this.actions,this.queryText)}handleKeyDown(e){if(KE(e))return;let t=this.filteredActions();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=h`
3763
+ `}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 nD(this.actions,this.queryText)}handleKeyDown(e){if(qE(e))return;let t=this.filteredActions();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=h`
3742
3764
  :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
3743
3765
  modal-surface { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); --modal-surface-place-items: start center; --modal-surface-backdrop-padding: var(--palette-top) 20px var(--palette-bottom); --modal-surface-max-height: min(640px, calc(100dvh - var(--palette-top) - var(--palette-bottom))); }
3744
3766
  header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid var(--pi-border); }
@@ -3760,7 +3782,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3760
3782
  .group { grid-column: 1 / -1; font-size: 12px; }
3761
3783
  kbd { align-self: center; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 2px 6px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
3762
3784
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
3763
- `}};H([b({attribute:!1})],eD.prototype,`actions`,void 0),H([b({attribute:!1})],eD.prototype,`onRun`,void 0),H([b({attribute:!1})],eD.prototype,`onCancel`,void 0),H([x()],eD.prototype,`queryText`,void 0),H([x()],eD.prototype,`selectedIndex`,void 0),eD=H([y(`action-palette`)],eD);function tD(e,t){let n=YE(t);return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||JE([e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `),n))}var nD=[`error`,`waiting`,`interrupted`,`active`,`unread`,`pinned`,`today`,`yesterday`,`earlier`],rD={error:`Needs attention`,waiting:`Waiting for you`,interrupted:`Interrupted`,active:`Working`,unread:`Finished`,pinned:`Pinned`,today:`Today`,yesterday:`Yesterday`,earlier:`Earlier`},iD=1440*60*1e3,aD=new Set;function oD(e){let t=e.sessions.filter(e=>e.archived!==!0).filter(t=>Gx(t,e.query)),n=new Map;for(let r of t){let t=sD(r,{active:e.activeSessionIds,error:e.errorSessionIds??aD,waiting:e.waitingSessionIds??aD,unread:e.unreadSessionIds??aD,interrupted:e.interruptedSessionIds??aD,pinned:e.pinnedSessionIds??aD},e.now),i=n.get(t)??[];i.push(r),n.set(t,i)}let r=[];for(let e of nD){let t=n.get(e);t===void 0||t.length===0||r.push({id:e,title:rD[e],sessions:t.sort(cD)})}return{groups:r,matchCount:t.length}}function sD(e,t,n){if(t.error.has(e.id))return`error`;if(t.waiting.has(e.id))return`waiting`;if(t.interrupted.has(e.id)&&!t.active.has(e.id))return`interrupted`;if(t.active.has(e.id))return`active`;if(t.unread.has(e.id))return`unread`;if(t.pinned.has(e.id))return`pinned`;let r=Date.parse(e.modified);if(Number.isNaN(r))return`earlier`;let i=n-r;return i<iD?`today`:i<2*iD?`yesterday`:`earlier`}function cD(e,t){return lD(t.modified)-lD(e.modified)}function lD(e){let t=Date.parse(e);return Number.isNaN(t)?0:t}function uD(e,t,n){let r=t.projectId===void 0?void 0:new Set(n.filter(e=>e.projectId===t.projectId).map(e=>e.path));return e.filter(e=>!(t.workspacePath!==void 0&&e.cwd!==t.workspacePath||r!==void 0&&!r.has(e.cwd)))}function dD(e){return e.machineId!==void 0||e.projectId!==void 0||e.workspacePath!==void 0}function fD(e,t){let n=t.trim().toLowerCase().split(/\s+/u).filter(Boolean);return n.length===0?[...e]:e.filter(e=>{let t=`${e.label}\n${e.path}`.toLowerCase();return n.every(e=>t.includes(e))})}function pD(e,t){let n=t.find(t=>t.path===e.cwd),r=`${String(e.messageCount)} ${e.messageCount===1?`message`:`messages`}`;return n===void 0?r:`${n.label} · ${r}`}function mD(e,t,n){return e.some(e=>e.id===t)?e.map(e=>e.id===t?{...e,name:n}:e):e}function hD(e,t,n){let r=new Map;for(let i of e){let e=xm(t[i.id],n[i.id]);e!==void 0&&r.set(i.id,e)}return r}var J=class extends v{constructor(...e){super(...e),this.loading=!1,this.sessions=[],this.workspaces=[],this.activeSessionIds=new Set,this.waitingSessionIds=new Set,this.unreadSessionIds=new Set,this.interruptedSessionIds=new Set,this.errorSessionIds=new Set,this.pinnedSessionIds=new Set,this.projects=[],this.sessionStates=new Map,this.canStartSession=!1,this.query=``,this.filter={},this.renameDraft=``,this.longPress=new qb({onLongPress:()=>{this.openMenuSessionId=this.heldSession?.id},setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>{window.clearTimeout(e)}})}render(){let e=this.model(),t=fD(this.workspaces,this.query).filter(e=>e.id!==this.selectedWorkspace?.id);return g`
3785
+ `}};H([b({attribute:!1})],tD.prototype,`actions`,void 0),H([b({attribute:!1})],tD.prototype,`onRun`,void 0),H([b({attribute:!1})],tD.prototype,`onCancel`,void 0),H([x()],tD.prototype,`queryText`,void 0),H([x()],tD.prototype,`selectedIndex`,void 0),tD=H([y(`action-palette`)],tD);function nD(e,t){let n=XE(t);return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||YE([e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `),n))}var rD=[`error`,`waiting`,`interrupted`,`active`,`unread`,`pinned`,`today`,`yesterday`,`earlier`],iD={error:`Needs attention`,waiting:`Waiting for you`,interrupted:`Interrupted`,active:`Working`,unread:`Finished`,pinned:`Pinned`,today:`Today`,yesterday:`Yesterday`,earlier:`Earlier`},aD=1440*60*1e3,oD=new Set;function sD(e){let t=e.sessions.filter(e=>e.archived!==!0).filter(t=>Gx(t,e.query)),n=new Map;for(let r of t){let t=cD(r,{active:e.activeSessionIds,error:e.errorSessionIds??oD,waiting:e.waitingSessionIds??oD,unread:e.unreadSessionIds??oD,interrupted:e.interruptedSessionIds??oD,pinned:e.pinnedSessionIds??oD},e.now),i=n.get(t)??[];i.push(r),n.set(t,i)}let r=[];for(let e of rD){let t=n.get(e);t===void 0||t.length===0||r.push({id:e,title:iD[e],sessions:t.sort(lD)})}return{groups:r,matchCount:t.length}}function cD(e,t,n){if(t.error.has(e.id))return`error`;if(t.waiting.has(e.id))return`waiting`;if(t.interrupted.has(e.id)&&!t.active.has(e.id))return`interrupted`;if(t.active.has(e.id))return`active`;if(t.unread.has(e.id))return`unread`;if(t.pinned.has(e.id))return`pinned`;let r=Date.parse(e.modified);if(Number.isNaN(r))return`earlier`;let i=n-r;return i<aD?`today`:i<2*aD?`yesterday`:`earlier`}function lD(e,t){return uD(t.modified)-uD(e.modified)}function uD(e){let t=Date.parse(e);return Number.isNaN(t)?0:t}function dD(e,t,n){let r=t.projectId===void 0?void 0:new Set(n.filter(e=>e.projectId===t.projectId).map(e=>e.path));return e.filter(e=>!(t.workspacePath!==void 0&&e.cwd!==t.workspacePath||r!==void 0&&!r.has(e.cwd)))}function fD(e){return e.machineId!==void 0||e.projectId!==void 0||e.workspacePath!==void 0}function pD(e,t){let n=t.trim().toLowerCase().split(/\s+/u).filter(Boolean);return n.length===0?[...e]:e.filter(e=>{let t=`${e.label}\n${e.path}`.toLowerCase();return n.every(e=>t.includes(e))})}function mD(e,t){let n=t.find(t=>t.path===e.cwd),r=`${String(e.messageCount)} ${e.messageCount===1?`message`:`messages`}`;return n===void 0?r:`${n.label} · ${r}`}function hD(e,t,n){return e.some(e=>e.id===t)?e.map(e=>e.id===t?{...e,name:n}:e):e}function gD(e,t,n){let r=new Map;for(let i of e){let e=xm(t[i.id],n[i.id]);e!==void 0&&r.set(i.id,e)}return r}var J=class extends v{constructor(...e){super(...e),this.loading=!1,this.sessions=[],this.workspaces=[],this.activeSessionIds=new Set,this.waitingSessionIds=new Set,this.unreadSessionIds=new Set,this.interruptedSessionIds=new Set,this.errorSessionIds=new Set,this.pinnedSessionIds=new Set,this.projects=[],this.sessionStates=new Map,this.canStartSession=!1,this.query=``,this.filter={},this.renameDraft=``,this.longPress=new qb({onLongPress:()=>{this.openMenuSessionId=this.heldSession?.id},setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>{window.clearTimeout(e)}})}render(){let e=this.model(),t=pD(this.workspaces,this.query).filter(e=>e.id!==this.selectedWorkspace?.id);return g`
3764
3786
  <modal-surface
3765
3787
  .onClose=${()=>this.onClose?.()}
3766
3788
  .initialFocus=${`input`}
@@ -3823,7 +3845,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3823
3845
  <button
3824
3846
  class=${`row session-row ${t?`selected`:``} ${n?`unread`:``}`}
3825
3847
  aria-current=${t?`true`:_}
3826
- ${OE(t,e.id)}
3848
+ ${kE(t,e.id)}
3827
3849
  @click=${()=>{this.openSession(e)}}
3828
3850
  @contextmenu=${t=>{t.preventDefault(),this.openMenuSessionId=e.id}}
3829
3851
  @pointerdown=${t=>{this.heldSession=e,this.longPress.start(t)}}
@@ -3832,7 +3854,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3832
3854
  @pointercancel=${()=>{this.longPress.cancel()}}
3833
3855
  >
3834
3856
  <span class="row-title" dir="auto">${r?g`<span class="pin-mark" title="Pinned" aria-label="Pinned">${`⚑`}</span> `:_}${Bx(e)}</span>
3835
- <span class="row-subtitle">${pD(e,this.workspaces)}</span>
3857
+ <span class="row-subtitle">${mD(e,this.workspaces)}</span>
3836
3858
  <span class="row-state">${ax(o,n&&o===void 0?`Unread activity`:void 0)}</span>
3837
3859
  ${a?g`<span class="row-flag interrupted" title="A restart interrupted this run" aria-label="A restart interrupted this run"></span>`:null}
3838
3860
  ${o===void 0&&!a&&n?g`<span class="row-flag unread" title="Unread activity" aria-label="Unread activity"></span>`:null}
@@ -3867,7 +3889,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3867
3889
  <button type="button" title="Cancel rename" aria-label="Cancel rename" @click=${()=>{this.renamingSessionId=void 0}}>${`×`}</button>
3868
3890
  </div>
3869
3891
  </form>
3870
- `}togglePin(e){this.openMenuSessionId=void 0,this.onTogglePin?.(e)}startRename(e){this.openMenuSessionId=void 0,this.renameDraft=Bx(e),this.renamingSessionId=e.id}async confirmRename(e){let t=this.renameDraft.trim();this.renamingSessionId=void 0,!(t===``||t===Bx(e))&&await this.onRenameSession?.(e,t)}handleKeyDown(e){if(e.key!==`Enter`||KE(e))return;let t=this.model().groups[0]?.sessions[0];t!==void 0&&(e.preventDefault(),this.openSession(t))}model(){return oD({sessions:uD(this.sessions,this.filter,this.workspaces),activeSessionIds:this.activeSessionIds,errorSessionIds:this.errorSessionIds,waitingSessionIds:this.waitingSessionIds,unreadSessionIds:this.unreadSessionIds,interruptedSessionIds:this.interruptedSessionIds,pinnedSessionIds:this.pinnedSessionIds,query:this.query,now:Date.now()})}renderFilters(){let e=this.projects.filter(e=>this.workspaces.some(t=>t.projectId===e.id));if(e.length===0&&this.workspaces.length<2)return _;let t=dD(this.filter);return g`
3892
+ `}togglePin(e){this.openMenuSessionId=void 0,this.onTogglePin?.(e)}startRename(e){this.openMenuSessionId=void 0,this.renameDraft=Bx(e),this.renamingSessionId=e.id}async confirmRename(e){let t=this.renameDraft.trim();this.renamingSessionId=void 0,!(t===``||t===Bx(e))&&await this.onRenameSession?.(e,t)}handleKeyDown(e){if(e.key!==`Enter`||qE(e))return;let t=this.model().groups[0]?.sessions[0];t!==void 0&&(e.preventDefault(),this.openSession(t))}model(){return sD({sessions:dD(this.sessions,this.filter,this.workspaces),activeSessionIds:this.activeSessionIds,errorSessionIds:this.errorSessionIds,waitingSessionIds:this.waitingSessionIds,unreadSessionIds:this.unreadSessionIds,interruptedSessionIds:this.interruptedSessionIds,pinnedSessionIds:this.pinnedSessionIds,query:this.query,now:Date.now()})}renderFilters(){let e=this.projects.filter(e=>this.workspaces.some(t=>t.projectId===e.id));if(e.length===0&&this.workspaces.length<2)return _;let t=fD(this.filter);return g`
3871
3893
  <div class="filters" role="group" aria-label="Filter sessions by context">
3872
3894
  <button
3873
3895
  type="button"
@@ -3968,7 +3990,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3968
3990
  .empty { margin: var(--pi-space-7) var(--pi-space-2); color: var(--pi-muted); }
3969
3991
  footer { flex: 0 0 auto; padding: var(--pi-space-5); padding-bottom: max(10px, env(safe-area-inset-bottom)); border-top: 1px solid var(--pi-border); }
3970
3992
  footer button { width: 100%; min-height: 44px; border: 1px solid var(--pi-border); border-radius: var(--pi-radius-lg); background: var(--pi-surface); color: var(--pi-text); cursor: pointer; }
3971
- `]}};H([b({type:Boolean})],J.prototype,`loading`,void 0),H([b({attribute:!1})],J.prototype,`sessions`,void 0),H([b({attribute:!1})],J.prototype,`workspaces`,void 0),H([b({attribute:!1})],J.prototype,`selectedSession`,void 0),H([b({attribute:!1})],J.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],J.prototype,`activeSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`waitingSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`unreadSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`interruptedSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`errorSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`pinnedSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`projects`,void 0),H([b({attribute:!1})],J.prototype,`sessionStates`,void 0),H([b({type:Boolean})],J.prototype,`canStartSession`,void 0),H([b({attribute:!1})],J.prototype,`onCreateSession`,void 0),H([b({attribute:!1})],J.prototype,`onOpenSession`,void 0),H([b({attribute:!1})],J.prototype,`onSelectWorkspace`,void 0),H([b({attribute:!1})],J.prototype,`onBrowse`,void 0),H([b({attribute:!1})],J.prototype,`onClose`,void 0),H([b({attribute:!1})],J.prototype,`onTogglePin`,void 0),H([b({attribute:!1})],J.prototype,`onRenameSession`,void 0),H([x()],J.prototype,`query`,void 0),H([x()],J.prototype,`filter`,void 0),H([x()],J.prototype,`openMenuSessionId`,void 0),H([x()],J.prototype,`renamingSessionId`,void 0),J=H([y(`quick-switcher`)],J);var gD=class extends v{constructor(...e){super(...e),this.selectedIndex=0,this.query=``}render(){let e=this.state;return e===void 0?null:g`
3993
+ `]}};H([b({type:Boolean})],J.prototype,`loading`,void 0),H([b({attribute:!1})],J.prototype,`sessions`,void 0),H([b({attribute:!1})],J.prototype,`workspaces`,void 0),H([b({attribute:!1})],J.prototype,`selectedSession`,void 0),H([b({attribute:!1})],J.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],J.prototype,`activeSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`waitingSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`unreadSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`interruptedSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`errorSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`pinnedSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`projects`,void 0),H([b({attribute:!1})],J.prototype,`sessionStates`,void 0),H([b({type:Boolean})],J.prototype,`canStartSession`,void 0),H([b({attribute:!1})],J.prototype,`onCreateSession`,void 0),H([b({attribute:!1})],J.prototype,`onOpenSession`,void 0),H([b({attribute:!1})],J.prototype,`onSelectWorkspace`,void 0),H([b({attribute:!1})],J.prototype,`onBrowse`,void 0),H([b({attribute:!1})],J.prototype,`onClose`,void 0),H([b({attribute:!1})],J.prototype,`onTogglePin`,void 0),H([b({attribute:!1})],J.prototype,`onRenameSession`,void 0),H([x()],J.prototype,`query`,void 0),H([x()],J.prototype,`filter`,void 0),H([x()],J.prototype,`openMenuSessionId`,void 0),H([x()],J.prototype,`renamingSessionId`,void 0),J=H([y(`quick-switcher`)],J);var _D=class extends v{constructor(...e){super(...e),this.selectedIndex=0,this.query=``}render(){let e=this.state;return e===void 0?null:g`
3972
3994
  <modal-surface
3973
3995
  .onClose=${()=>{this.cancel()}}
3974
3996
  .initialFocus=${this.initialFocusTarget(e)}
@@ -3981,7 +4003,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3981
4003
  </header>
3982
4004
  ${this.renderBody(e)}
3983
4005
  </modal-surface>
3984
- `}optionsFor(e){switch(e.step){case`method`:return[{key:`oauth`,title:`Use a subscription`,detail:`ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot`,searchText:`Use a subscription`,run:()=>{this.onChooseMethod?.(`oauth`)}},{key:`api_key`,title:`Use provider credentials`,detail:`Configure an API key or provider-specific credentials in the active Pi-compatible profile's auth.json`,searchText:`Use provider credentials`,run:()=>{this.onChooseMethod?.(`api_key`)}}];case`providers`:return e.providers.map(e=>({key:e.id,title:g`${e.name}${e.status.source===void 0?null:g` <em>${TD(e)}</em>`}`,detail:`${e.id} · ${xD(e.authType)}`,searchText:e.name,run:()=>{this.onSelectProvider?.(e.id,e.authType)}}));case`logout`:return e.providers.map(e=>({key:e.id,title:e.name,detail:`${e.id} · ${xD(e.authType)}`,searchText:e.name,run:()=>{this.onLogoutProvider?.(e.id)}}));case`oauth`:return}}initialFocusTarget(e){if(e.step===`oauth`)return e.flow.prompt===void 0?void 0:`input`;if(e.step===`providers`||e.step===`logout`)return e.providers.length>0?`input`:void 0}stepHasSearch(e){return e.step===`providers`||e.step===`logout`}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(e){let t=YE(this.query);return t===``?e:e.filter(e=>JE(`${e.searchText} ${e.detail} ${e.key}`,t))}visibleOptions(e){let t=this.optionsFor(e);return t===void 0?[]:this.filteredOptions(t)}willUpdate(e){if(!e.has(`state`))return;if(wD(e.get(`state`))!==this.state?.step){this.selectedIndex=0,this.query=``;return}let t=this.state===void 0?void 0:this.visibleOptions(this.state);t!==void 0&&(this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,t.length-1)))}updated(e){if(!e.has(`state`))return;let t=wD(e.get(`state`));if(t===void 0)return;let n=this.state?.step,r=t!==n,i=t===`oauth`&&n===`oauth`&&SD(e.get(`state`))!==SD(this.state);(r||i)&&this.surface?.focusDialog()}dialogTitle(e){switch(e.step){case`method`:return`Configure provider authentication`;case`providers`:return e.authType===void 0?`Select provider authentication`:e.authType===`oauth`?`Select subscription provider`:`Select credential provider`;case`oauth`:return`Login to ${e.flow.providerName}`;case`logout`:return`Remove stored provider authentication`}}renderBody(e){if(e.step===`oauth`)return this.renderOAuth(e);let t=this.optionsFor(e)??[],n=this.filteredOptions(t);return g`
4006
+ `}optionsFor(e){switch(e.step){case`method`:return[{key:`oauth`,title:`Use a subscription`,detail:`ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot`,searchText:`Use a subscription`,run:()=>{this.onChooseMethod?.(`oauth`)}},{key:`api_key`,title:`Use provider credentials`,detail:`Configure an API key or provider-specific credentials in the active Pi-compatible profile's auth.json`,searchText:`Use provider credentials`,run:()=>{this.onChooseMethod?.(`api_key`)}}];case`providers`:return e.providers.map(e=>({key:e.id,title:g`${e.name}${e.status.source===void 0?null:g` <em>${ED(e)}</em>`}`,detail:`${e.id} · ${SD(e.authType)}`,searchText:e.name,run:()=>{this.onSelectProvider?.(e.id,e.authType)}}));case`logout`:return e.providers.map(e=>({key:e.id,title:e.name,detail:`${e.id} · ${SD(e.authType)}`,searchText:e.name,run:()=>{this.onLogoutProvider?.(e.id)}}));case`oauth`:return}}initialFocusTarget(e){if(e.step===`oauth`)return e.flow.prompt===void 0?void 0:`input`;if(e.step===`providers`||e.step===`logout`)return e.providers.length>0?`input`:void 0}stepHasSearch(e){return e.step===`providers`||e.step===`logout`}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(e){let t=XE(this.query);return t===``?e:e.filter(e=>YE(`${e.searchText} ${e.detail} ${e.key}`,t))}visibleOptions(e){let t=this.optionsFor(e);return t===void 0?[]:this.filteredOptions(t)}willUpdate(e){if(!e.has(`state`))return;if(TD(e.get(`state`))!==this.state?.step){this.selectedIndex=0,this.query=``;return}let t=this.state===void 0?void 0:this.visibleOptions(this.state);t!==void 0&&(this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,t.length-1)))}updated(e){if(!e.has(`state`))return;let t=TD(e.get(`state`));if(t===void 0)return;let n=this.state?.step,r=t!==n,i=t===`oauth`&&n===`oauth`&&CD(e.get(`state`))!==CD(this.state);(r||i)&&this.surface?.focusDialog()}dialogTitle(e){switch(e.step){case`method`:return`Configure provider authentication`;case`providers`:return e.authType===void 0?`Select provider authentication`:e.authType===`oauth`?`Select subscription provider`:`Select credential provider`;case`oauth`:return`Login to ${e.flow.providerName}`;case`logout`:return`Remove stored provider authentication`}}renderBody(e){if(e.step===`oauth`)return this.renderOAuth(e);let t=this.optionsFor(e)??[],n=this.filteredOptions(t);return g`
3985
4007
  ${this.stepHasSearch(e)&&t.length>0?g`
3986
4008
  <input aria-label="Search providers" placeholder="Search providers" .value=${this.query} @input=${e=>{this.handleSearchInput(e)}}>
3987
4009
  `:null}
@@ -3990,7 +4012,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3990
4012
  <button
3991
4013
  class=${t===this.selectedIndex?`selected`:``}
3992
4014
  aria-current=${t===this.selectedIndex?`true`:_}
3993
- ${OE(t===this.selectedIndex,e.key)}
4015
+ ${kE(t===this.selectedIndex,e.key)}
3994
4016
  @focus=${()=>{this.selectedIndex=t}}
3995
4017
  @click=${()=>{e.run()}}
3996
4018
  >
@@ -3999,7 +4021,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3999
4021
  </button>
4000
4022
  `)}
4001
4023
  </div>
4002
- `}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=n===void 0?void 0:_D(n.promptType),a=bD(e.machineId,window.location.hostname)&&t.status===`running`&&n?.promptType===`manual_code`;return g`
4024
+ `}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=n===void 0?void 0:vD(n.promptType),a=xD(e.machineId,window.location.hostname)&&t.status===`running`&&n?.promptType===`manual_code`;return g`
4003
4025
  <div class="form">
4004
4026
  ${t.auth===void 0?g`<p>Starting login flow…</p>`:g`
4005
4027
  <p>Open this authorization link:</p>
@@ -4033,7 +4055,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4033
4055
  ${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}
4034
4056
  ${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
4035
4057
  </div>
4036
- `}handleKeyDown(e){let t=this.state;if(t===void 0||KE(e))return;if(e.key===`ArrowDown`||e.key===`ArrowUp`){let n=this.visibleOptions(t);if(n.length===0)return;e.preventDefault();let r=e.key===`ArrowDown`?1:-1;this.selectedIndex=(this.selectedIndex+r+n.length)%n.length;return}if(e.key!==`Enter`)return;if(t.step===`oauth`){if(t.flow.prompt===void 0)return;e.preventDefault(),this.onOAuthRespond?.();return}let n=this.visibleOptions(t)[this.selectedIndex];n!==void 0&&(e.preventDefault(),n.run())}cancel(){this.state?.step===`oauth`?this.onOAuthCancel?.():this.onCancel?.()}static{this.styles=[h`
4058
+ `}handleKeyDown(e){let t=this.state;if(t===void 0||qE(e))return;if(e.key===`ArrowDown`||e.key===`ArrowUp`){let n=this.visibleOptions(t);if(n.length===0)return;e.preventDefault();let r=e.key===`ArrowDown`?1:-1;this.selectedIndex=(this.selectedIndex+r+n.length)%n.length;return}if(e.key!==`Enter`)return;if(t.step===`oauth`){if(t.flow.prompt===void 0)return;e.preventDefault(),this.onOAuthRespond?.();return}let n=this.visibleOptions(t)[this.selectedIndex];n!==void 0&&(e.preventDefault(),n.run())}cancel(){this.state?.step===`oauth`?this.onOAuthCancel?.():this.onCancel?.()}static{this.styles=[h`
4037
4059
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
4038
4060
  modal-surface { --modal-surface-width: min(720px, calc(100vw - 40px)); --modal-surface-max-height: min(640px, calc(100vh - 40px)); }
4039
4061
  header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
@@ -4068,7 +4090,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4068
4090
  .inline-options button { display: grid; gap: 2px; text-align: left; }
4069
4091
  .inline-options small { color: var(--pi-muted); }
4070
4092
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
4071
- `]}};H([b({attribute:!1})],gD.prototype,`state`,void 0),H([b({attribute:!1})],gD.prototype,`onChooseMethod`,void 0),H([b({attribute:!1})],gD.prototype,`onSelectProvider`,void 0),H([b({attribute:!1})],gD.prototype,`onLogoutProvider`,void 0),H([b({attribute:!1})],gD.prototype,`onOAuthInput`,void 0),H([b({attribute:!1})],gD.prototype,`onOAuthRespond`,void 0),H([b({attribute:!1})],gD.prototype,`onOAuthCancel`,void 0),H([b({attribute:!1})],gD.prototype,`onCancel`,void 0),H([S(`modal-surface`)],gD.prototype,`surface`,void 0),H([x()],gD.prototype,`selectedIndex`,void 0),H([x()],gD.prototype,`query`,void 0),gD=H([y(`auth-dialog`)],gD);function _D(e){return e===`secret`?`password`:`text`}var vD=new Set([`localhost`,`127.0.0.1`,`::1`]);function yD(e){return vD.has(e.trim().replace(/^\[|\]$/g,``).toLowerCase())}function bD(e,t){return e!==`local`||!yD(t)}function xD(e){return e===`oauth`?`subscription`:`credentials`}function SD(e){if(wD(e)!==`oauth`||typeof e!=`object`||!e||!(`flow`in e))return;let t=e.flow;if(typeof t!=`object`||!t)return;let n=`flowId`in t&&typeof t.flowId==`string`?t.flowId:``,r=`prompt`in t?CD(t.prompt):void 0;if(r!==void 0)return`${n}:prompt:${r}:${`responding`in e&&e.responding===!0?`responding`:`ready`}`;let i=`select`in t?CD(t.select):void 0;return i===void 0?`${n}:waiting:${`status`in t&&typeof t.status==`string`?t.status:`unknown`}`:`${n}:select:${i}`}function CD(e){if(!(typeof e!=`object`||!e||!(`requestId`in e)))return typeof e.requestId==`string`?e.requestId:void 0}function wD(e){if(!(typeof e!=`object`||!e||!(`step`in e)))switch(e.step){case`method`:case`providers`:case`oauth`:case`logout`:return e.step;default:return}}function TD(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 ED=120,DD=class extends v{constructor(...e){super(...e),this.machineId=`local`,this.path=``,this.createMissing=!0,this.submitError=void 0,this.submitting=!1,this.suggestions=[],this.selected=0,this.loading=!1,this.trustTouched=!1,this.suggestionRequestId=0,this.trustRequestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}disconnectedCallback(){this.cancelPendingSuggestions(),super.disconnectedCallback()}scheduleSuggestions(){this.cancelPendingSuggestions(),this.suggestionTimer=setTimeout(()=>{this.suggestionTimer=void 0,this.loadSuggestions()},ED)}cancelPendingSuggestions(){this.suggestionTimer!==void 0&&(clearTimeout(this.suggestionTimer),this.suggestionTimer=void 0)}async loadSuggestions(){let e=++this.suggestionRequestId;this.loading=!0;try{let t=await I.projectDirectories(this.path,this.machineId);if(e!==this.suggestionRequestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.suggestionRequestId&&(this.suggestions=[])}finally{e===this.suggestionRequestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.scheduleSuggestions(),this.trustTouched=!1,this.loadTrust()}pick(e){this.path=e.path,this.selected=0,this.cancelPendingSuggestions(),this.loadSuggestions()}submit(){this.path.trim()===``||this.submitting||(this.submitError=void 0,this.submitting=!0,(async()=>{try{let e=await this.onSubmit?.(this.path,this.createMissing,this.trust===void 0?void 0:{trusted:this.trust.trusted,changed:this.trustTouched});this.submitError=typeof e==`string`&&e!==``?e:void 0}finally{this.submitting=!1}})())}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}async loadTrust(){let e=++this.trustRequestId,t=this.path.trim();if(t===``){e===this.trustRequestId&&(this.trust=void 0);return}e===this.trustRequestId&&(this.trust={...this.trust??{path:t,decision:null,trusted:!1},path:t,loading:!0});try{let n=await Wo.projectTrust(t,this.machineId);if(e!==this.trustRequestId||this.trustTouched)return;this.trust={path:n.path,decision:n.decision,trusted:n.trusted,loading:!1}}catch(n){if(e!==this.trustRequestId||this.trustTouched)return;this.trust={path:t,decision:null,trusted:!1,loading:!1,error:n instanceof Error?n.message:String(n)}}}onTrustChange(e){this.trustTouched=!0,this.trust!==void 0&&(this.trust={...this.trust,trusted:e,loading:!1})}renderTrustChoice(){let e=this.trust===void 0||this.trust.loading||this.trust.error!==void 0;return g`
4093
+ `]}};H([b({attribute:!1})],_D.prototype,`state`,void 0),H([b({attribute:!1})],_D.prototype,`onChooseMethod`,void 0),H([b({attribute:!1})],_D.prototype,`onSelectProvider`,void 0),H([b({attribute:!1})],_D.prototype,`onLogoutProvider`,void 0),H([b({attribute:!1})],_D.prototype,`onOAuthInput`,void 0),H([b({attribute:!1})],_D.prototype,`onOAuthRespond`,void 0),H([b({attribute:!1})],_D.prototype,`onOAuthCancel`,void 0),H([b({attribute:!1})],_D.prototype,`onCancel`,void 0),H([S(`modal-surface`)],_D.prototype,`surface`,void 0),H([x()],_D.prototype,`selectedIndex`,void 0),H([x()],_D.prototype,`query`,void 0),_D=H([y(`auth-dialog`)],_D);function vD(e){return e===`secret`?`password`:`text`}var yD=new Set([`localhost`,`127.0.0.1`,`::1`]);function bD(e){return yD.has(e.trim().replace(/^\[|\]$/g,``).toLowerCase())}function xD(e,t){return e!==`local`||!bD(t)}function SD(e){return e===`oauth`?`subscription`:`credentials`}function CD(e){if(TD(e)!==`oauth`||typeof e!=`object`||!e||!(`flow`in e))return;let t=e.flow;if(typeof t!=`object`||!t)return;let n=`flowId`in t&&typeof t.flowId==`string`?t.flowId:``,r=`prompt`in t?wD(t.prompt):void 0;if(r!==void 0)return`${n}:prompt:${r}:${`responding`in e&&e.responding===!0?`responding`:`ready`}`;let i=`select`in t?wD(t.select):void 0;return i===void 0?`${n}:waiting:${`status`in t&&typeof t.status==`string`?t.status:`unknown`}`:`${n}:select:${i}`}function wD(e){if(!(typeof e!=`object`||!e||!(`requestId`in e)))return typeof e.requestId==`string`?e.requestId:void 0}function TD(e){if(!(typeof e!=`object`||!e||!(`step`in e)))switch(e.step){case`method`:case`providers`:case`oauth`:case`logout`:return e.step;default:return}}function ED(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 DD=120,OD=class extends v{constructor(...e){super(...e),this.machineId=`local`,this.path=``,this.createMissing=!0,this.submitError=void 0,this.submitting=!1,this.suggestions=[],this.selected=0,this.loading=!1,this.trustTouched=!1,this.suggestionRequestId=0,this.trustRequestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}disconnectedCallback(){this.cancelPendingSuggestions(),super.disconnectedCallback()}scheduleSuggestions(){this.cancelPendingSuggestions(),this.suggestionTimer=setTimeout(()=>{this.suggestionTimer=void 0,this.loadSuggestions()},DD)}cancelPendingSuggestions(){this.suggestionTimer!==void 0&&(clearTimeout(this.suggestionTimer),this.suggestionTimer=void 0)}async loadSuggestions(){let e=++this.suggestionRequestId;this.loading=!0;try{let t=await I.projectDirectories(this.path,this.machineId);if(e!==this.suggestionRequestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.suggestionRequestId&&(this.suggestions=[])}finally{e===this.suggestionRequestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.scheduleSuggestions(),this.trustTouched=!1,this.loadTrust()}pick(e){this.path=e.path,this.selected=0,this.cancelPendingSuggestions(),this.loadSuggestions()}submit(){this.path.trim()===``||this.submitting||(this.submitError=void 0,this.submitting=!0,(async()=>{try{let e=await this.onSubmit?.(this.path,this.createMissing,this.trust===void 0?void 0:{trusted:this.trust.trusted,changed:this.trustTouched});this.submitError=typeof e==`string`&&e!==``?e:void 0}finally{this.submitting=!1}})())}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}async loadTrust(){let e=++this.trustRequestId,t=this.path.trim();if(t===``){e===this.trustRequestId&&(this.trust=void 0);return}e===this.trustRequestId&&(this.trust={...this.trust??{path:t,decision:null,trusted:!1},path:t,loading:!0});try{let n=await Wo.projectTrust(t,this.machineId);if(e!==this.trustRequestId||this.trustTouched)return;this.trust={path:n.path,decision:n.decision,trusted:n.trusted,loading:!1}}catch(n){if(e!==this.trustRequestId||this.trustTouched)return;this.trust={path:t,decision:null,trusted:!1,loading:!1,error:n instanceof Error?n.message:String(n)}}}onTrustChange(e){this.trustTouched=!0,this.trust!==void 0&&(this.trust={...this.trust,trusted:e,loading:!1})}renderTrustChoice(){let e=this.trust===void 0||this.trust.loading||this.trust.error!==void 0;return g`
4072
4094
  <label class="check">
4073
4095
  <input type="checkbox" .checked=${this.trust?.trusted??!1} ?disabled=${e} @change=${e=>{e.target instanceof HTMLInputElement&&this.onTrustChange(e.target.checked)}} />
4074
4096
  <span>Trust this project</span>
@@ -4155,7 +4177,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4155
4177
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
4156
4178
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
4157
4179
  button:disabled { opacity: .5; cursor: not-allowed; }
4158
- `}};H([b({attribute:!1})],DD.prototype,`onSubmit`,void 0),H([b({attribute:!1})],DD.prototype,`onCancel`,void 0),H([b()],DD.prototype,`machineId`,void 0),H([x()],DD.prototype,`path`,void 0),H([x()],DD.prototype,`createMissing`,void 0),H([x()],DD.prototype,`submitError`,void 0),H([x()],DD.prototype,`submitting`,void 0),H([x()],DD.prototype,`suggestions`,void 0),H([x()],DD.prototype,`selected`,void 0),H([x()],DD.prototype,`loading`,void 0),H([x()],DD.prototype,`trust`,void 0),H([x()],DD.prototype,`trustTouched`,void 0),H([S(`input`)],DD.prototype,`pathInput`,void 0),DD=H([y(`project-dialog`)],DD);var OD=class extends v{constructor(...e){super(...e),this.error=``,this.url=``,this.name=``,this.token=``,this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=``}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;let t=e.target.value,n=kD(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){e.key===`Enter`&&e.target instanceof HTMLInputElement&&e.target.name===`baseUrl`&&AD(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===``||AD(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?AD(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
4180
+ `}};H([b({attribute:!1})],OD.prototype,`onSubmit`,void 0),H([b({attribute:!1})],OD.prototype,`onCancel`,void 0),H([b()],OD.prototype,`machineId`,void 0),H([x()],OD.prototype,`path`,void 0),H([x()],OD.prototype,`createMissing`,void 0),H([x()],OD.prototype,`submitError`,void 0),H([x()],OD.prototype,`submitting`,void 0),H([x()],OD.prototype,`suggestions`,void 0),H([x()],OD.prototype,`selected`,void 0),H([x()],OD.prototype,`loading`,void 0),H([x()],OD.prototype,`trust`,void 0),H([x()],OD.prototype,`trustTouched`,void 0),H([S(`input`)],OD.prototype,`pathInput`,void 0),OD=H([y(`project-dialog`)],OD);var kD=class extends v{constructor(...e){super(...e),this.error=``,this.url=``,this.name=``,this.token=``,this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=``}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;let t=e.target.value,n=AD(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){e.key===`Enter`&&e.target instanceof HTMLInputElement&&e.target.name===`baseUrl`&&jD(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===``||jD(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?jD(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
4159
4181
  <modal-surface
4160
4182
  .onClose=${()=>this.onCancel?.()}
4161
4183
  .initialFocus=${`input[name='baseUrl']`}
@@ -4214,7 +4236,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4214
4236
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
4215
4237
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
4216
4238
  button:disabled { opacity: .5; cursor: not-allowed; }
4217
- `}};H([b({attribute:!1})],OD.prototype,`onSubmit`,void 0),H([b({attribute:!1})],OD.prototype,`onCancel`,void 0),H([b()],OD.prototype,`error`,void 0),H([x()],OD.prototype,`url`,void 0),H([x()],OD.prototype,`name`,void 0),H([x()],OD.prototype,`token`,void 0),H([x()],OD.prototype,`submitting`,void 0),H([S(`input[name='name']`)],OD.prototype,`nameInput`,void 0),OD=H([y(`machine-dialog`)],OD);function kD(e){let t=e.trim();if(t===``)return``;let n=jD(t)??jD(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):MD(t)}function AD(e){let t=e.trim();if(t===``)return`Remote PI WEB 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 jD(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function MD(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 ND=class extends v{constructor(...e){super(...e),this.themes=[],this.followSystem=!1}render(){return g`
4239
+ `}};H([b({attribute:!1})],kD.prototype,`onSubmit`,void 0),H([b({attribute:!1})],kD.prototype,`onCancel`,void 0),H([b()],kD.prototype,`error`,void 0),H([x()],kD.prototype,`url`,void 0),H([x()],kD.prototype,`name`,void 0),H([x()],kD.prototype,`token`,void 0),H([x()],kD.prototype,`submitting`,void 0),H([S(`input[name='name']`)],kD.prototype,`nameInput`,void 0),kD=H([y(`machine-dialog`)],kD);function AD(e){let t=e.trim();if(t===``)return``;let n=MD(t)??MD(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):ND(t)}function jD(e){let t=e.trim();if(t===``)return`Remote PI WEB 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 MD(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function ND(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 PD=class extends v{constructor(...e){super(...e),this.themes=[],this.followSystem=!1}render(){return g`
4218
4240
  <settings-panel-frame>
4219
4241
  <div class="heading">
4220
4242
  <div>
@@ -4300,7 +4322,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4300
4322
  .theme-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: var(--pi-space-4); }
4301
4323
  .preview { height: 64px; }
4302
4324
  }
4303
- `}};H([b({attribute:!1})],ND.prototype,`themes`,void 0),H([b({attribute:!1})],ND.prototype,`selectedThemeId`,void 0),H([b({attribute:!1})],ND.prototype,`activeThemeId`,void 0),H([b({type:Boolean})],ND.prototype,`followSystem`,void 0),H([b({attribute:!1})],ND.prototype,`onSelectTheme`,void 0),H([b({attribute:!1})],ND.prototype,`onToggleFollowSystem`,void 0),ND=H([y(`settings-appearance-panel`)],ND);var PD={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function FD(e){return e.tone??PD[e.type]}var ID=class extends v{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
4325
+ `}};H([b({attribute:!1})],PD.prototype,`themes`,void 0),H([b({attribute:!1})],PD.prototype,`selectedThemeId`,void 0),H([b({attribute:!1})],PD.prototype,`activeThemeId`,void 0),H([b({type:Boolean})],PD.prototype,`followSystem`,void 0),H([b({attribute:!1})],PD.prototype,`onSelectTheme`,void 0),H([b({attribute:!1})],PD.prototype,`onToggleFollowSystem`,void 0),PD=H([y(`settings-appearance-panel`)],PD);var FD={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function ID(e){return e.tone??FD[e.type]}var LD=class extends v{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
4304
4326
  <section class="panel" aria-label=${this.heading||`Settings panel`}>
4305
4327
  <header class="section-heading">
4306
4328
  <div class="heading-copy">
@@ -4323,7 +4345,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4323
4345
  <div class="notice-stack" aria-label="Settings notices">
4324
4346
  ${this.notices.map(e=>this.renderNotice(e))}
4325
4347
  </div>
4326
- `}renderNotice(e){let t=FD(e),n=e.role??LD(t),r=e.title;return g`
4348
+ `}renderNotice(e){let t=ID(e),n=e.role??RD(t),r=e.title;return g`
4327
4349
  <article class=${`notice ${t}`} role=${n}>
4328
4350
  ${r===void 0||r===``?_:g`<strong class="notice-title">${r}</strong>`}
4329
4351
  <div class="notice-content">${e.content}</div>
@@ -4356,13 +4378,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4356
4378
  .section-heading { display: grid; gap: 12px; }
4357
4379
  .heading-actions { justify-self: start; }
4358
4380
  }
4359
- `}};H([b()],ID.prototype,`heading`,void 0),H([b({attribute:!1})],ID.prototype,`description`,void 0),H([b()],ID.prototype,`actionLabel`,void 0),H([b()],ID.prototype,`actionTitle`,void 0),H([b({type:Boolean})],ID.prototype,`actionDisabled`,void 0),H([b({attribute:!1})],ID.prototype,`notices`,void 0),H([b({attribute:!1})],ID.prototype,`onAction`,void 0),ID=H([y(`settings-panel-frame`)],ID);function LD(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function RD(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function zD(){return{allowedPathsText:``,uploadDefaultFolder:``}}function BD(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(`
4360
- `):``}}function VD(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
4361
- `)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function HD(e,t={}){let n=WD(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`||GD(e.allowedHostsText),n}function UD(e){let t=KD(e.allowedPathsText),n=qD(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function WD(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.askUser===void 0?{}:{askUser:e.askUser},...e.agent===void 0?{}:{agent:e.agent}}}function GD(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function KD(e){let t=e.split(`
4362
- `).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!JD(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function qD(e){let t=e.trim();if(t===``)return``;if(YD(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 JD(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function YD(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function XD(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var Y=class extends v{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=RD(),this.machineDraft=zD(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=BD(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=VD(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
4381
+ `}};H([b()],LD.prototype,`heading`,void 0),H([b({attribute:!1})],LD.prototype,`description`,void 0),H([b()],LD.prototype,`actionLabel`,void 0),H([b()],LD.prototype,`actionTitle`,void 0),H([b({type:Boolean})],LD.prototype,`actionDisabled`,void 0),H([b({attribute:!1})],LD.prototype,`notices`,void 0),H([b({attribute:!1})],LD.prototype,`onAction`,void 0),LD=H([y(`settings-panel-frame`)],LD);function RD(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function zD(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function BD(){return{allowedPathsText:``,uploadDefaultFolder:``}}function VD(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(`
4382
+ `):``}}function HD(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
4383
+ `)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function UD(e,t={}){let n=GD(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`||KD(e.allowedHostsText),n}function WD(e){let t=qD(e.allowedPathsText),n=JD(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function GD(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.askUser===void 0?{}:{askUser:e.askUser},...e.agent===void 0?{}:{agent:e.agent}}}function KD(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function qD(e){let t=e.split(`
4384
+ `).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!YD(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function JD(e){let t=e.trim();if(t===``)return``;if(XD(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 YD(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function XD(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function ZD(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var Y=class extends v{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=zD(),this.machineDraft=BD(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=VD(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=HD(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
4363
4385
  <settings-panel-frame
4364
4386
  heading="General configuration"
4365
- .description=${XD(this.targetLabel)}
4387
+ .description=${ZD(this.targetLabel)}
4366
4388
  actionLabel="Reload"
4367
4389
  .actionDisabled=${this.loading||this.machineLoading}
4368
4390
  .notices=${this.panelNotices()}
@@ -4391,7 +4413,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4391
4413
  <span>Host</span>
4392
4414
  ${this.renderOverrideBadge(`host`)}
4393
4415
  </span>
4394
- <input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:$D(e)})}}>
4416
+ <input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:eO(e)})}}>
4395
4417
  <small>Address the web server should bind to. Leave empty to use PI WEB's default.</small>
4396
4418
  </label>
4397
4419
 
@@ -4400,7 +4422,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4400
4422
  <span>Port</span>
4401
4423
  ${this.renderOverrideBadge(`port`)}
4402
4424
  </span>
4403
- <input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:$D(e)})}}>
4425
+ <input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:eO(e)})}}>
4404
4426
  <small>TCP port from 1 to 65535. Leave empty to use PI WEB's default.</small>
4405
4427
  </label>
4406
4428
 
@@ -4409,11 +4431,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4409
4431
  <span>Allowed hosts</span>
4410
4432
  ${this.renderOverrideBadge(`allowedHosts`)}
4411
4433
  </span>
4412
- <select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:eO(e)===`all`?`all`:`list`})}}>
4434
+ <select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:tO(e)===`all`?`all`:`list`})}}>
4413
4435
  <option value="list">Only listed hosts</option>
4414
4436
  <option value="all">Allow every host</option>
4415
4437
  </select>
4416
- <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:tO(e)})}}></textarea>
4438
+ <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:nO(e)})}}></textarea>
4417
4439
  <small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
4418
4440
  </div>
4419
4441
 
@@ -4443,7 +4465,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4443
4465
  <span class="field-heading">
4444
4466
  <span>External filesystem roots</span>
4445
4467
  </span>
4446
- <textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:tO(e)})}}></textarea>
4468
+ <textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:nO(e)})}}></textarea>
4447
4469
  <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>
4448
4470
  </label>
4449
4471
 
@@ -4451,7 +4473,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4451
4473
  <span class="field-heading">
4452
4474
  <span>Default upload folder</span>
4453
4475
  </span>
4454
- <input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${vs} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:$D(e)})}}>
4476
+ <input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${vs} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:eO(e)})}}>
4455
4477
  <small>Workspace-relative folder for manual file uploads on ${this.targetLabel}. Leave empty to use PI WEB's default <code>${vs}</code>.</small>
4456
4478
  </label>
4457
4479
 
@@ -4469,18 +4491,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4469
4491
  <dl>
4470
4492
  <div><dt>Host</dt><dd>${e.host??g`<span class="muted">127.0.0.1 default</span>`}</dd></div>
4471
4493
  <div><dt>Port</dt><dd>${e.port??g`<span class="muted">8504 default</span>`}</dd></div>
4472
- <div><dt>Allowed hosts</dt><dd>${ZD(e.allowedHosts)}</dd></div>
4494
+ <div><dt>Allowed hosts</dt><dd>${QD(e.allowedHosts)}</dd></div>
4473
4495
  </dl>
4474
4496
  </section>
4475
4497
  `}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
4476
4498
  <section class="effective-card" aria-label="Effective selected machine file access and upload summary">
4477
4499
  <h3>Effective selected-machine settings</h3>
4478
4500
  <dl>
4479
- <div><dt>External roots</dt><dd>${QD(e.pathAccess?.allowedPaths)}</dd></div>
4501
+ <div><dt>External roots</dt><dd>${$D(e.pathAccess?.allowedPaths)}</dd></div>
4480
4502
  <div><dt>Upload folder</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">${`.pi-web/uploads`} default</span>`}</dd></div>
4481
4503
  </dl>
4482
4504
  </section>
4483
- `}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(HD(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=nO(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(UD(this.machineDraft))}catch(e){this.machineLocalError=nO(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
4505
+ `}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(UD(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=rO(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(WD(this.machineDraft))}catch(e){this.machineLocalError=rO(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
4484
4506
  :host { display: block; }
4485
4507
  .card-heading { display: grid; gap: 6px; min-width: 0; }
4486
4508
  h3, p { margin: 0; }
@@ -4519,7 +4541,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4519
4541
  @media (max-width: 760px) {
4520
4542
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
4521
4543
  }
4522
- `}};H([b({attribute:!1})],Y.prototype,`configResponse`,void 0),H([b({attribute:!1})],Y.prototype,`machineConfigResponse`,void 0),H([b({type:Boolean})],Y.prototype,`loading`,void 0),H([b({type:Boolean})],Y.prototype,`machineLoading`,void 0),H([b({type:Boolean})],Y.prototype,`saving`,void 0),H([b()],Y.prototype,`error`,void 0),H([b()],Y.prototype,`machineError`,void 0),H([b()],Y.prototype,`savedMessage`,void 0),H([b()],Y.prototype,`targetLabel`,void 0),H([b({attribute:!1})],Y.prototype,`onReload`,void 0),H([b({attribute:!1})],Y.prototype,`onReloadMachine`,void 0),H([b({attribute:!1})],Y.prototype,`onSave`,void 0),H([b({attribute:!1})],Y.prototype,`onSaveMachineConfig`,void 0),H([x()],Y.prototype,`gatewayDraft`,void 0),H([x()],Y.prototype,`machineDraft`,void 0),H([x()],Y.prototype,`gatewayLocalError`,void 0),H([x()],Y.prototype,`machineLocalError`,void 0),Y=H([y(`settings-general-panel`)],Y);function ZD(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 QD(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function $D(e){return e.target instanceof HTMLInputElement?e.target.value:``}function eO(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function tO(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function nO(e){return e instanceof Error?e.message:String(e)}var rO=class extends v{constructor(...e){super(...e),this.loading=!1}render(){let e=this.report?.machines??[];return g`
4544
+ `}};H([b({attribute:!1})],Y.prototype,`configResponse`,void 0),H([b({attribute:!1})],Y.prototype,`machineConfigResponse`,void 0),H([b({type:Boolean})],Y.prototype,`loading`,void 0),H([b({type:Boolean})],Y.prototype,`machineLoading`,void 0),H([b({type:Boolean})],Y.prototype,`saving`,void 0),H([b()],Y.prototype,`error`,void 0),H([b()],Y.prototype,`machineError`,void 0),H([b()],Y.prototype,`savedMessage`,void 0),H([b()],Y.prototype,`targetLabel`,void 0),H([b({attribute:!1})],Y.prototype,`onReload`,void 0),H([b({attribute:!1})],Y.prototype,`onReloadMachine`,void 0),H([b({attribute:!1})],Y.prototype,`onSave`,void 0),H([b({attribute:!1})],Y.prototype,`onSaveMachineConfig`,void 0),H([x()],Y.prototype,`gatewayDraft`,void 0),H([x()],Y.prototype,`machineDraft`,void 0),H([x()],Y.prototype,`gatewayLocalError`,void 0),H([x()],Y.prototype,`machineLocalError`,void 0),Y=H([y(`settings-general-panel`)],Y);function QD(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 $D(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function eO(e){return e.target instanceof HTMLInputElement?e.target.value:``}function tO(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function nO(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function rO(e){return e instanceof Error?e.message:String(e)}var iO=class extends v{constructor(...e){super(...e),this.loading=!1}render(){let e=this.report?.machines??[];return g`
4523
4545
  <section class="fleet">
4524
4546
  <header>
4525
4547
  <div>
@@ -4601,7 +4623,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4601
4623
  .machine { grid-template-columns: auto minmax(0, 1fr); }
4602
4624
  .machine .row-actions { grid-row: auto; grid-column: 1 / -1; }
4603
4625
  }
4604
- `}};H([b({attribute:!1})],rO.prototype,`report`,void 0),H([b({type:Boolean})],rO.prototype,`loading`,void 0),H([b({attribute:!1})],rO.prototype,`error`,void 0),H([b({attribute:!1})],rO.prototype,`onRefresh`,void 0),H([b({attribute:!1})],rO.prototype,`onRun`,void 0),H([x()],rO.prototype,`running`,void 0),H([x()],rO.prototype,`lastRun`,void 0),rO=H([y(`settings-fleet-section`)],rO);var iO=class extends v{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.fleetLoading=!1,this.draftName=``}render(){return g`
4626
+ `}};H([b({attribute:!1})],iO.prototype,`report`,void 0),H([b({type:Boolean})],iO.prototype,`loading`,void 0),H([b({attribute:!1})],iO.prototype,`error`,void 0),H([b({attribute:!1})],iO.prototype,`onRefresh`,void 0),H([b({attribute:!1})],iO.prototype,`onRun`,void 0),H([x()],iO.prototype,`running`,void 0),H([x()],iO.prototype,`lastRun`,void 0),iO=H([y(`settings-fleet-section`)],iO);var aO=class extends v{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.fleetLoading=!1,this.draftName=``}render(){return g`
4605
4627
  <settings-panel-frame>
4606
4628
  <div class="machines-heading">
4607
4629
  <div>
@@ -4674,10 +4696,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4674
4696
  .machine-grid { grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: var(--pi-space-3); }
4675
4697
  .machine-card { min-height: 88px; padding: var(--pi-space-4); }
4676
4698
  }
4677
- `}};H([b({attribute:!1})],iO.prototype,`machines`,void 0),H([b({attribute:!1})],iO.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],iO.prototype,`onAdd`,void 0),H([b({attribute:!1})],iO.prototype,`onRename`,void 0),H([b({attribute:!1})],iO.prototype,`onRemove`,void 0),H([b({attribute:!1})],iO.prototype,`fleetReport`,void 0),H([b({type:Boolean})],iO.prototype,`fleetLoading`,void 0),H([b({attribute:!1})],iO.prototype,`fleetError`,void 0),H([b({attribute:!1})],iO.prototype,`onRefreshFleet`,void 0),H([b({attribute:!1})],iO.prototype,`onRunFleet`,void 0),H([x()],iO.prototype,`renamingId`,void 0),H([x()],iO.prototype,`draftName`,void 0),iO=H([y(`settings-machines-panel`)],iO);function aO(e){return{spawnSessions:e}}function oO(e){return{subsessions:e}}function sO(e){return{askUser:e}}function cO(e,t){return{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:{...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions,askUser:t.envOverrides.askUser}}}var lO=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}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.askUser===!0,o=e?.effectiveConfig.askUser===!0;return g`
4699
+ `}};H([b({attribute:!1})],aO.prototype,`machines`,void 0),H([b({attribute:!1})],aO.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],aO.prototype,`onAdd`,void 0),H([b({attribute:!1})],aO.prototype,`onRename`,void 0),H([b({attribute:!1})],aO.prototype,`onRemove`,void 0),H([b({attribute:!1})],aO.prototype,`fleetReport`,void 0),H([b({type:Boolean})],aO.prototype,`fleetLoading`,void 0),H([b({attribute:!1})],aO.prototype,`fleetError`,void 0),H([b({attribute:!1})],aO.prototype,`onRefreshFleet`,void 0),H([b({attribute:!1})],aO.prototype,`onRunFleet`,void 0),H([x()],aO.prototype,`renamingId`,void 0),H([x()],aO.prototype,`draftName`,void 0),aO=H([y(`settings-machines-panel`)],aO);function oO(e){return{spawnSessions:e}}function sO(e){return{subsessions:e}}function cO(e){return{askUser:e}}function lO(e,t){return{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:{...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions,askUser:t.envOverrides.askUser}}}var uO=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}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.askUser===!0,o=e?.effectiveConfig.askUser===!0;return g`
4678
4700
  <settings-panel-frame
4679
4701
  heading="Session daemon"
4680
- .description=${uO(this.targetLabel)}
4702
+ .description=${dO(this.targetLabel)}
4681
4703
  actionLabel="Reload"
4682
4704
  .actionDisabled=${this.loading}
4683
4705
  .notices=${this.panelNotices()}
@@ -4747,7 +4769,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4747
4769
  </section>
4748
4770
  `}
4749
4771
  </settings-panel-frame>
4750
- `}panelNotices(){return dO({error:this.error,savedMessage:this.savedMessage})}renderUnavailableConfigState(){return g`<div class="loading-card">${this.loading?`Loading configuration…`:`Configuration is unavailable. Reload to try again.`}</div>`}async toggleSpawnSessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(aO(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(oO(t))}async toggleAskUser(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(sO(t))}static{this.styles=h`
4772
+ `}panelNotices(){return fO({error:this.error,savedMessage:this.savedMessage})}renderUnavailableConfigState(){return g`<div class="loading-card">${this.loading?`Loading configuration…`:`Configuration is unavailable. Reload to try again.`}</div>`}async toggleSpawnSessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(oO(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(sO(t))}async toggleAskUser(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(cO(t))}static{this.styles=h`
4751
4773
  :host { display: block; }
4752
4774
  h3 { margin: 0; font-size: 13px; line-height: 1.3; }
4753
4775
  .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
@@ -4771,10 +4793,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4771
4793
  @media (max-width: 760px) {
4772
4794
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
4773
4795
  }
4774
- `}};H([b({attribute:!1})],lO.prototype,`configResponse`,void 0),H([b({type:Boolean})],lO.prototype,`loading`,void 0),H([b({type:Boolean})],lO.prototype,`saving`,void 0),H([b()],lO.prototype,`error`,void 0),H([b()],lO.prototype,`savedMessage`,void 0),H([b()],lO.prototype,`targetLabel`,void 0),H([b({attribute:!1})],lO.prototype,`onReload`,void 0),H([b({attribute:!1})],lO.prototype,`onSave`,void 0),lO=H([y(`settings-sessiond-panel`)],lO);function uO(e){return`Agent tool capabilities for sessions on ${e}. Changes are saved immediately but only take effect after the session daemon on that machine restarts.`}function dO(e){let t=[];return e.error!==``&&t.push({type:`error`,content:e.error}),e.savedMessage!==``&&t.push({type:`success`,content:e.savedMessage}),t}function fO(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function pO(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function mO(e){return e.kind===`local`}function hO(e){return e.trim()}function gO(e){if(hO(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function _O(e){return e.scope===`project`?`Project scope`:`User scope`}function vO(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEB process`}function yO(e){return e.installedPath??`Installed path not reported by Pi`}function bO(e){return e.scope===`user`}function xO(e){if(!bO(e))return`Project-scope Pi packages are listed for visibility, but PI WEB only updates user-scope Pi packages safely from this view.`}function SO(e){return e.length>0&&e.every(bO)}function CO(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!SO(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function wO(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function TO(e,t=fO(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 WEB session`:`each idle PI WEB 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 WEB browser plugin changes`:`PI WEB browser plugin changes served by ${t.name}`}.`}function EO(e,t){let n=e.trim();return t.kind===`remote`?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}var DO=class extends v{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=pO(t),r=this.packagesResponse!==void 0;return g`
4796
+ `}};H([b({attribute:!1})],uO.prototype,`configResponse`,void 0),H([b({type:Boolean})],uO.prototype,`loading`,void 0),H([b({type:Boolean})],uO.prototype,`saving`,void 0),H([b()],uO.prototype,`error`,void 0),H([b()],uO.prototype,`savedMessage`,void 0),H([b()],uO.prototype,`targetLabel`,void 0),H([b({attribute:!1})],uO.prototype,`onReload`,void 0),H([b({attribute:!1})],uO.prototype,`onSave`,void 0),uO=H([y(`settings-sessiond-panel`)],uO);function dO(e){return`Agent tool capabilities for sessions on ${e}. Changes are saved immediately but only take effect after the session daemon on that machine restarts.`}function fO(e){let t=[];return e.error!==``&&t.push({type:`error`,content:e.error}),e.savedMessage!==``&&t.push({type:`success`,content:e.savedMessage}),t}function pO(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function mO(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function hO(e){return e.kind===`local`}function gO(e){return e.trim()}function _O(e){if(gO(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function vO(e){return e.scope===`project`?`Project scope`:`User scope`}function yO(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEB process`}function bO(e){return e.installedPath??`Installed path not reported by Pi`}function xO(e){return e.scope===`user`}function SO(e){if(!xO(e))return`Project-scope Pi packages are listed for visibility, but PI WEB only updates user-scope Pi packages safely from this view.`}function CO(e){return e.length>0&&e.every(xO)}function wO(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!CO(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function TO(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function EO(e,t=pO(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 WEB session`:`each idle PI WEB 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 WEB browser plugin changes`:`PI WEB browser plugin changes served by ${t.name}`}.`}function DO(e,t){let n=e.trim();return t.kind===`remote`?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}var OO=class extends v{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=mO(t),r=this.packagesResponse!==void 0;return g`
4775
4797
  <settings-panel-frame
4776
4798
  heading="Pi packages"
4777
- .description=${OO(n)}
4799
+ .description=${kO(n)}
4778
4800
  actionLabel="Reload"
4779
4801
  actionTitle=${`Reload Pi packages from ${n}`}
4780
4802
  .actionDisabled=${this.loading||this.isOperating}
@@ -4791,12 +4813,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4791
4813
  <label for="package-source">Pi package source</label>
4792
4814
  <div class="install-row">
4793
4815
  <input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package, git URL, or local path" @input=${e=>{this.updateInstallSource(e)}}>
4794
- <button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${wO(this.operation,`install`)?`Installing…`:`Install`}</button>
4816
+ <button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${TO(this.operation,`install`)?`Installing…`:`Install`}</button>
4795
4817
  </div>
4796
4818
  ${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
4797
4819
  <small>Installs run on ${e} and use Pi's default package location, equivalent to <code>pi install &lt;source&gt;</code>. PI WEB does not ask you to choose an install location.</small>
4798
4820
  </form>
4799
- `}renderPackageList(e,t){let n=pO(t),r=CO(e),i=r!==void 0&&e.length>0;return g`
4821
+ `}renderPackageList(e,t){let n=mO(t),r=wO(e),i=r!==void 0&&e.length>0;return g`
4800
4822
  <section class="package-section" aria-label="Configured Pi packages">
4801
4823
  <div class="package-toolbar">
4802
4824
  <div>
@@ -4804,7 +4826,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4804
4826
  <p>This list comes from Pi's package manager settings on ${n}.</p>
4805
4827
  </div>
4806
4828
  <button class="secondary" title=${r??`Update all user-scope Pi packages`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
4807
- ${wO(this.operation,`update-all`)?`Updating…`:`Update all`}
4829
+ ${TO(this.operation,`update-all`)?`Updating…`:`Update all`}
4808
4830
  </button>
4809
4831
  </div>
4810
4832
  ${i?g`<div class="action-note">${r}</div>`:null}
@@ -4815,12 +4837,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4815
4837
  <div class="package-list">
4816
4838
  ${e.map(e=>this.renderPackage(e))}
4817
4839
  </div>
4818
- `}renderPackage(e){let t=xO(e),n=wO(this.operation,`update`,e.source),r=wO(this.operation,`remove`,e.source);return g`
4840
+ `}renderPackage(e){let t=SO(e),n=TO(this.operation,`update`,e.source),r=TO(this.operation,`remove`,e.source);return g`
4819
4841
  <article class=${`package-card${e.filtered?` filtered`:``}`}>
4820
4842
  <div class="package-main">
4821
4843
  <strong>${e.source}</strong>
4822
- <small>${_O(e)} · ${vO(e)}</small>
4823
- <small>Installed path: <code>${yO(e)}</code></small>
4844
+ <small>${vO(e)} · ${yO(e)}</small>
4845
+ <small>Installed path: <code>${bO(e)}</code></small>
4824
4846
  ${t===void 0?null:g`<small class="action-note">${t}</small>`}
4825
4847
  </div>
4826
4848
  <div class="package-actions">
@@ -4828,7 +4850,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4828
4850
  <button class="danger" title="Remove this Pi package" ?disabled=${this.isOperating} @click=${()=>{this.removePackage(e)}}>${r?`Removing…`:`Remove`}</button>
4829
4851
  </div>
4830
4852
  </article>
4831
- `}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=gO(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=hO(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??fO(void 0)}get isOperating(){return this.operation!==void 0}static{this.styles=h`
4853
+ `}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=_O(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=gO(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??pO(void 0)}get isOperating(){return this.operation!==void 0}static{this.styles=h`
4832
4854
  :host { display: block; }
4833
4855
  .package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
4834
4856
  .package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
@@ -4863,10 +4885,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4863
4885
  .package-actions { justify-self: start; flex-wrap: wrap; }
4864
4886
  .package-main strong, .package-main small { white-space: normal; }
4865
4887
  }
4866
- `}};H([b({attribute:!1})],DO.prototype,`packagesResponse`,void 0),H([b({type:Boolean})],DO.prototype,`loading`,void 0),H([b({attribute:!1})],DO.prototype,`operation`,void 0),H([b({attribute:!1})],DO.prototype,`targetMachine`,void 0),H([b()],DO.prototype,`error`,void 0),H([b()],DO.prototype,`operationMessage`,void 0),H([b({attribute:!1})],DO.prototype,`onReload`,void 0),H([b({attribute:!1})],DO.prototype,`onInstallPackage`,void 0),H([b({attribute:!1})],DO.prototype,`onRemovePackage`,void 0),H([b({attribute:!1})],DO.prototype,`onUpdatePackage`,void 0),H([x()],DO.prototype,`installSource`,void 0),H([x()],DO.prototype,`validationMessage`,void 0),DO=H([y(`settings-packages-panel`)],DO);function OO(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 WEB browser plugins.`}var kO=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.recoveryCommandsSupported=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}render(){let e=AO(this.pluginsResponse,this.configResponse),t=this.pluginsResponse!==void 0;return g`
4888
+ `}};H([b({attribute:!1})],OO.prototype,`packagesResponse`,void 0),H([b({type:Boolean})],OO.prototype,`loading`,void 0),H([b({attribute:!1})],OO.prototype,`operation`,void 0),H([b({attribute:!1})],OO.prototype,`targetMachine`,void 0),H([b()],OO.prototype,`error`,void 0),H([b()],OO.prototype,`operationMessage`,void 0),H([b({attribute:!1})],OO.prototype,`onReload`,void 0),H([b({attribute:!1})],OO.prototype,`onInstallPackage`,void 0),H([b({attribute:!1})],OO.prototype,`onRemovePackage`,void 0),H([b({attribute:!1})],OO.prototype,`onUpdatePackage`,void 0),H([x()],OO.prototype,`installSource`,void 0),H([x()],OO.prototype,`validationMessage`,void 0),OO=H([y(`settings-packages-panel`)],OO);function kO(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 WEB browser plugins.`}var AO=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.recoveryCommandsSupported=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}render(){let e=jO(this.pluginsResponse,this.configResponse),t=this.pluginsResponse!==void 0;return g`
4867
4889
  <settings-panel-frame
4868
4890
  heading="PI WEB plugins"
4869
- .description=${PO(this.targetLabel)}
4891
+ .description=${FO(this.targetLabel)}
4870
4892
  actionLabel="Reload"
4871
4893
  actionTitle=${`Reload PI WEB plugins from ${this.targetLabel}`}
4872
4894
  .actionDisabled=${this.loading}
@@ -4905,11 +4927,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4905
4927
  </article>
4906
4928
  `}renderPluginStatuses(e){let t=e.server;return g`
4907
4929
  <div class="status-list" aria-label=${`${e.id} plugin states`}>
4908
- ${t===void 0?g`<span class="status neutral">${e.configOnly?`Configured only`:`Browser only`}</span>`:g`<span class=${`status ${MO(t.state)}`}>${jO(t.state)}</span>`}
4930
+ ${t===void 0?g`<span class="status neutral">${e.configOnly?`Configured only`:`Browser only`}</span>`:g`<span class=${`status ${NO(t.state)}`}>${MO(t.state)}</span>`}
4909
4931
  ${e.conflict?g`<span class="status error">Conflict</span>`:_}
4910
4932
  ${t?.staleRevision===!0?g`<span class="status warning">Stale revision</span>`:_}
4911
4933
  ${t?.restartRequired===!0?g`<span class="status warning">Restart required</span>`:_}
4912
- ${t?.health===void 0?_:g`<span class=${`status ${NO(t.health.status)}`}>Health ${t.health.status}</span>`}
4934
+ ${t?.health===void 0?_:g`<span class=${`status ${PO(t.health.status)}`}>Health ${t.health.status}</span>`}
4913
4935
  </div>
4914
4936
  `}renderRecoveryCommands(){let e=this.pluginsResponse?.serverRuntime,t=(e?.status===`incompatible`&&!this.recoveryCommandsSupported?void 0:e?.recovery)??(this.recoveryCommandsSupported?nn:void 0);return t===void 0?_:g`
4915
4937
  <aside class="recovery" aria-label="Offline server-plugin recovery commands">
@@ -4950,10 +4972,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4950
4972
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
4951
4973
  .toggle { justify-self: start; }
4952
4974
  }
4953
- `}};H([b({attribute:!1})],kO.prototype,`pluginsResponse`,void 0),H([b({attribute:!1})],kO.prototype,`configResponse`,void 0),H([b({type:Boolean})],kO.prototype,`loading`,void 0),H([b({type:Boolean})],kO.prototype,`saving`,void 0),H([b({type:Boolean})],kO.prototype,`recoveryCommandsSupported`,void 0),H([b()],kO.prototype,`error`,void 0),H([b()],kO.prototype,`savedMessage`,void 0),H([b()],kO.prototype,`targetLabel`,void 0),H([b({attribute:!1})],kO.prototype,`onReload`,void 0),H([b({attribute:!1})],kO.prototype,`onTogglePlugin`,void 0),kO=H([y(`settings-plugins-panel`)],kO);function AO(e,t){let n=t?.config.plugins??{},r=(e?.plugins??[]).map(e=>{let t=n[e.id],r=t?.enabled??e.enabled;return{...e,enabled:r,configOnly:!1,editable:e.discovered||t!==void 0}}),i=new Set(r.map(({id:e})=>e));for(let[e,t]of Object.entries(n))i.has(e)||r.push({id:e,source:`config`,scope:`local`,machineSpecific:!1,enabled:t.enabled!==!1,discovered:!1,conflict:!1,configOnly:!0,editable:!0});return r.sort((e,t)=>e.id.localeCompare(t.id))}function jO(e){switch(e){case`active`:return`Active`;case`failed`:return`Failed`;case`incompatible`:return`Incompatible`;case`disabled`:return`Disabled`;case`missing`:return`Not active`;case`unknown`:return`Active state unavailable`}}function MO(e){switch(e){case`active`:return`success`;case`disabled`:case`missing`:return`warning`;case`failed`:case`incompatible`:return`error`;case`unknown`:return`neutral`}}function NO(e){switch(e){case`healthy`:return`success`;case`degraded`:return`warning`;case`unhealthy`:return`error`}}function PO(e){return g`Compare desired plugin config with the active sessiond startup snapshot on <strong>${e}</strong>. This is separate from installing Pi packages.`}var FO={capture:!0},IO=[{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 RO=class extends v{constructor(...e){super(...e),this.actions=[],this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.drafts={},this.localError=``,this.promptEnterPreference=YT(),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=Jp(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&&!Yp(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=HO(this.actions),t=this.shortcutResolutions();return g`
4975
+ `}};H([b({attribute:!1})],AO.prototype,`pluginsResponse`,void 0),H([b({attribute:!1})],AO.prototype,`configResponse`,void 0),H([b({type:Boolean})],AO.prototype,`loading`,void 0),H([b({type:Boolean})],AO.prototype,`saving`,void 0),H([b({type:Boolean})],AO.prototype,`recoveryCommandsSupported`,void 0),H([b()],AO.prototype,`error`,void 0),H([b()],AO.prototype,`savedMessage`,void 0),H([b()],AO.prototype,`targetLabel`,void 0),H([b({attribute:!1})],AO.prototype,`onReload`,void 0),H([b({attribute:!1})],AO.prototype,`onTogglePlugin`,void 0),AO=H([y(`settings-plugins-panel`)],AO);function jO(e,t){let n=t?.config.plugins??{},r=(e?.plugins??[]).map(e=>{let t=n[e.id],r=t?.enabled??e.enabled;return{...e,enabled:r,configOnly:!1,editable:e.discovered||t!==void 0}}),i=new Set(r.map(({id:e})=>e));for(let[e,t]of Object.entries(n))i.has(e)||r.push({id:e,source:`config`,scope:`local`,machineSpecific:!1,enabled:t.enabled!==!1,discovered:!1,conflict:!1,configOnly:!0,editable:!0});return r.sort((e,t)=>e.id.localeCompare(t.id))}function MO(e){switch(e){case`active`:return`Active`;case`failed`:return`Failed`;case`incompatible`:return`Incompatible`;case`disabled`:return`Disabled`;case`missing`:return`Not active`;case`unknown`:return`Active state unavailable`}}function NO(e){switch(e){case`active`:return`success`;case`disabled`:case`missing`:return`warning`;case`failed`:case`incompatible`:return`error`;case`unknown`:return`neutral`}}function PO(e){switch(e){case`healthy`:return`success`;case`degraded`:return`warning`;case`unhealthy`:return`error`}}function FO(e){return g`Compare desired plugin config with the active sessiond startup snapshot on <strong>${e}</strong>. This is separate from installing Pi packages.`}var IO={capture:!0},LO=[{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 RO(){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 zO=class extends v{constructor(...e){super(...e),this.actions=[],this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.drafts={},this.localError=``,this.promptEnterPreference=XT(),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=Jp(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&&!Yp(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=UO(this.actions),t=this.shortcutResolutions();return g`
4954
4976
  <settings-panel-frame
4955
4977
  heading="Keyboard shortcuts"
4956
- .description=${LO()}
4978
+ .description=${RO()}
4957
4979
  actionLabel="Reload"
4958
4980
  .actionDisabled=${this.loading}
4959
4981
  .notices=${this.panelNotices()}
@@ -4984,7 +5006,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4984
5006
  <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>
4985
5007
  </div>
4986
5008
  <div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
4987
- ${IO.map(e=>g`
5009
+ ${LO.map(e=>g`
4988
5010
  <label class="prompt-enter-option">
4989
5011
  <input
4990
5012
  type="radio"
@@ -5001,8 +5023,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5001
5023
  `)}
5002
5024
  </div>
5003
5025
  </section>
5004
- `}updatePromptEnterPreference(e){this.promptEnterPreference=e,XT(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=Zp(e,n),i=KO(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Gp(a),s=o?.ok===!0?o.shortcut:GO(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=VO(t);return g`
5005
- <article class=${zO(t)}>
5026
+ `}updatePromptEnterPreference(e){this.promptEnterPreference=e,ZT(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=Zp(e,n),i=qO(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Gp(a),s=o?.ok===!0?o.shortcut:KO(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=HO(t);return g`
5027
+ <article class=${BO(t)}>
5006
5028
  <div class="shortcut-main">
5007
5029
  <strong>${e.title}</strong>
5008
5030
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
@@ -5012,8 +5034,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5012
5034
  <div class="shortcut-editor">
5013
5035
  <div class="shortcut-status">
5014
5036
  ${s!==void 0&&s!==``?g`<kbd>${qp(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`Disabled`:`Unassigned`}</span>`}
5015
- <small class=${u}>${qO(u)}${l?` · Unsaved`:``}</small>
5016
- ${f===void 0?null:g`<small class=${BO(t)}>${f}</small>`}
5037
+ <small class=${u}>${JO(u)}${l?` · Unsaved`:``}</small>
5038
+ ${f===void 0?null:g`<small class=${VO(t)}>${f}</small>`}
5017
5039
  </div>
5018
5040
  <label class="shortcut-input-label">
5019
5041
  <span>Shortcut</span>
@@ -5026,7 +5048,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5026
5048
  autocapitalize="off"
5027
5049
  spellcheck="false"
5028
5050
  ?disabled=${this.saving}
5029
- @input=${t=>{this.updateDraft(e.id,JO(t))}}
5051
+ @input=${t=>{this.updateDraft(e.id,YO(t))}}
5030
5052
  >
5031
5053
  </label>
5032
5054
  ${d===``?null:g`<small class="recording-hint">${d}</small>`}
@@ -5038,7 +5060,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5038
5060
  </div>
5039
5061
  </div>
5040
5062
  </article>
5041
- `}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=Zp(e,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: ${qp(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=Gp(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e,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=WO(n.shortcuts??{},[e.id,...e.shortcutAliases??[]]),i=t===void 0?r:{...r,[e.id]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Wp(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=Gp(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()},Vp)}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,FO),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,FO),!1)}static{this.styles=h`
5063
+ `}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=Zp(e,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: ${qp(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=Gp(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e,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=GO(n.shortcuts??{},[e.id,...e.shortcutAliases??[]]),i=t===void 0?r:{...r,[e.id]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Wp(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=Gp(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()},Vp)}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,IO),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,IO),!1)}static{this.styles=h`
5042
5064
  :host { display: block; }
5043
5065
  h3, p { margin: 0; }
5044
5066
  h3 { font-size: 13px; line-height: 1.3; }
@@ -5094,7 +5116,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5094
5116
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
5095
5117
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
5096
5118
  }
5097
- `}};H([b({attribute:!1})],RO.prototype,`actions`,void 0),H([b({attribute:!1})],RO.prototype,`configResponse`,void 0),H([b({type:Boolean})],RO.prototype,`loading`,void 0),H([b({type:Boolean})],RO.prototype,`saving`,void 0),H([b()],RO.prototype,`error`,void 0),H([b()],RO.prototype,`savedMessage`,void 0),H([b({attribute:!1})],RO.prototype,`onReload`,void 0),H([b({attribute:!1})],RO.prototype,`onSave`,void 0),H([x()],RO.prototype,`drafts`,void 0),H([x()],RO.prototype,`localError`,void 0),H([x()],RO.prototype,`promptEnterPreference`,void 0),H([x()],RO.prototype,`recording`,void 0),RO=H([y(`settings-shortcuts-panel`)],RO);function zO(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function BO(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function VO(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 HO(e){let t=new Map;for(let n of[...e].sort(UO)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function UO(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function WO(e,t){let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function GO(e,t){let n=Zp(e,t);if(n!==null)return n??e.shortcut}function KO(e,t){let n=Zp(e,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function qO(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function JO(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function YO(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: ${ZO(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEB plugins: ${ZO(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function XO(e,t){try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${pO(e)}: ${EO(ZO(t),e)}`}}}function ZO(e){return e instanceof Error?e.message:String(e)}function QO(e,t){return{...e,config:$O(e.config,t.config),effectiveConfig:$O(e.effectiveConfig,t.effectiveConfig)}}function $O(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 ek(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function tk(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function nk(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?qt(t,kt.pluginLifecycle)?{state:`supported`}:{state:`unsupported`,message:ak(e)}:{state:`unknown`}}function rk(e){return`${e.state}:${e.message??``}`}function ik(e){return e?.state===`unsupported`}function ak(e){return`Plugin lifecycle diagnostics are not available on ${e.name}. Update and restart PI WEB on that machine before loading server-backed plugins.`}function ok(e,t){let n=e.trim();return t.kind===`remote`?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 sk(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function ck(e,t){return{...e,config:lk(e.config,t.config),effectiveConfig:lk(e.effectiveConfig,t.effectiveConfig)}}function lk(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var X=class extends v{constructor(...e){super(...e),this.section=`general`,this.actions=[],this.machines=[],this.machineStatuses={},this.themes=[],this.followSystemTheme=!1,this.fleetLoading=!1,this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){let t=this.settingsTarget();if(e.has(`machine`)&&ek(e.get(`machine`)).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t);return}e.has(`machineRuntime`)&&this.pluginLifecycleSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t))}render(){return g`
5119
+ `}};H([b({attribute:!1})],zO.prototype,`actions`,void 0),H([b({attribute:!1})],zO.prototype,`configResponse`,void 0),H([b({type:Boolean})],zO.prototype,`loading`,void 0),H([b({type:Boolean})],zO.prototype,`saving`,void 0),H([b()],zO.prototype,`error`,void 0),H([b()],zO.prototype,`savedMessage`,void 0),H([b({attribute:!1})],zO.prototype,`onReload`,void 0),H([b({attribute:!1})],zO.prototype,`onSave`,void 0),H([x()],zO.prototype,`drafts`,void 0),H([x()],zO.prototype,`localError`,void 0),H([x()],zO.prototype,`promptEnterPreference`,void 0),H([x()],zO.prototype,`recording`,void 0),zO=H([y(`settings-shortcuts-panel`)],zO);function BO(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function VO(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function HO(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 UO(e){let t=new Map;for(let n of[...e].sort(WO)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function WO(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function GO(e,t){let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function KO(e,t){let n=Zp(e,t);if(n!==null)return n??e.shortcut}function qO(e,t){let n=Zp(e,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function JO(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function YO(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: ${QO(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEB plugins: ${QO(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function ZO(e,t){try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${mO(e)}: ${DO(QO(t),e)}`}}}function QO(e){return e instanceof Error?e.message:String(e)}function $O(e,t){return{...e,config:ek(e.config,t.config),effectiveConfig:ek(e.effectiveConfig,t.effectiveConfig)}}function ek(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 tk(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function nk(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function rk(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?qt(t,kt.pluginLifecycle)?{state:`supported`}:{state:`unsupported`,message:ok(e)}:{state:`unknown`}}function ik(e){return`${e.state}:${e.message??``}`}function ak(e){return e?.state===`unsupported`}function ok(e){return`Plugin lifecycle diagnostics are not available on ${e.name}. Update and restart PI WEB on that machine before loading server-backed plugins.`}function sk(e,t){let n=e.trim();return t.kind===`remote`?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 ck(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function lk(e,t){return{...e,config:uk(e.config,t.config),effectiveConfig:uk(e.effectiveConfig,t.effectiveConfig)}}function uk(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var X=class extends v{constructor(...e){super(...e),this.section=`general`,this.actions=[],this.machines=[],this.machineStatuses={},this.themes=[],this.followSystemTheme=!1,this.fleetLoading=!1,this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){let t=this.settingsTarget();if(e.has(`machine`)&&tk(e.get(`machine`)).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t);return}e.has(`machineRuntime`)&&this.pluginLifecycleSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t))}render(){return g`
5098
5120
  <modal-surface .onClose=${()=>this.onClose?.()} .label=${`PI WEB settings`}>
5099
5121
  <header class="settings-header">
5100
5122
  <div>
@@ -5147,7 +5169,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5147
5169
  .saving=${this.saving}
5148
5170
  .error=${this.sessiondError}
5149
5171
  .savedMessage=${this.savedMessage}
5150
- .targetLabel=${tk(this.settingsTarget())}
5172
+ .targetLabel=${nk(this.settingsTarget())}
5151
5173
  .onReload=${()=>this.reloadSessiondState()}
5152
5174
  .onSave=${e=>this.saveSessiondConfig(e)}
5153
5175
  ></settings-sessiond-panel>
@@ -5184,7 +5206,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5184
5206
  .recoveryCommandsSupported=${this.pluginLifecycleSupport().state===`supported`}
5185
5207
  .error=${this.pluginError}
5186
5208
  .savedMessage=${this.savedMessage}
5187
- .targetLabel=${tk(this.settingsTarget())}
5209
+ .targetLabel=${nk(this.settingsTarget())}
5188
5210
  .onReload=${()=>this.loadPluginsForTarget()}
5189
5211
  .onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
5190
5212
  ></settings-plugins-panel>
@@ -5198,7 +5220,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5198
5220
  .error=${this.error}
5199
5221
  .machineError=${this.accessError}
5200
5222
  .savedMessage=${this.savedMessage}
5201
- .targetLabel=${tk(this.settingsTarget())}
5223
+ .targetLabel=${nk(this.settingsTarget())}
5202
5224
  .onReload=${()=>this.loadConfig()}
5203
5225
  .onReloadMachine=${()=>this.loadAccessConfigForTarget()}
5204
5226
  .onSave=${e=>this.saveConfig(e)}
@@ -5209,7 +5231,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5209
5231
  <strong>${t}</strong>
5210
5232
  <small>${n}</small>
5211
5233
  </button>
5212
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await YO({loadConfig:()=>xo.config(),loadPlugins:()=>Co.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;this.accessLoading=!0,this.accessError=``;try{let n=await xo.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 ${tk(e)}: ${ok(uk(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;this.sessiondLoading=!0,this.sessiondError=``;try{let n=await xo.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 ${tk(e)}: ${ok(uk(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq;this.pluginLoading=!0,this.pluginError=``;try{let n=this.pluginLifecycleSupport(e);if(ik(n)){try{let r=await xo.config(e.id);if(!this.isCurrentPluginLoad(t,e))return;this.selectedPluginConfigResponse=r,this.selectedPluginsResponse=void 0,this.pluginError=n.message??`Plugin lifecycle diagnostics are not available on ${tk(e)}.`}catch(r){if(!this.isCurrentPluginLoad(t,e))return;this.pluginError=`Failed to load PI WEB plugin config from ${tk(e)}: ${ok(uk(r),e)}; ${n.message??`plugin lifecycle diagnostics are unsupported`}`}return}let[r,i]=await Promise.allSettled([xo.config(e.id),Co.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let a=[];r.status===`fulfilled`?this.selectedPluginConfigResponse=r.value:a.push(`config: ${ok(uk(r.reason),e)}`),i.status===`fulfilled`?this.selectedPluginsResponse=i.value:a.push(`PI WEB plugins: ${ok(uk(i.reason),e)}`),this.pluginError=a.length===0?``:`Failed to load PI WEB plugin settings from ${tk(e)}: ${a.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 XO(e,e=>Do.packages(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.pluginLifecycleSupport(n);if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${tk(n)}. Reload before changing plugin enablement.`;return}let i=sk(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await xo.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=ck(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t;if(ik(r)?(this.selectedPluginsResponse=void 0,t=r.message??`Plugin lifecycle diagnostics are not available on ${tk(n)}.`):t=await this.refreshPluginsForTarget(n),!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEB plugin config on ${tk(n)}: ${ok(uk(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await xo.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${uk(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget();this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await xo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=QO(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 ${tk(t)}: ${ok(uk(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget();this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await xo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=cO(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${tk(t)}: ${ok(uk(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>Do.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>Do.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,()=>Do.update(e,t.id))}async runPiPackageMutation(e,t,n,r){if(this.saving)throw Error(`A settings operation is already running.`);let i=++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(i,n))return;this.packagesResponse={packages:e.packages};let t=mO(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(i,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=TO(e.action,n)}catch(e){throw this.isCurrentPackageMutation(i,n)&&(this.packageError=`Failed to ${t} on ${pO(n)}: ${EO(uk(e),n)}`),e}finally{this.packageMutationSeq===i&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Co.plugins();return}catch(e){return`Failed to refresh gateway PI WEB plugins: ${uk(e)}`}}async refreshPluginsForTarget(e){try{let t=await Co.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=void 0),`Config saved, but failed to refresh PI WEB plugins from ${tk(e)}: ${ok(uk(t),e)}`}}settingsTarget(){return ek(this.machine)}packageTarget(){return this.settingsTarget()}pluginLifecycleSupport(e=this.settingsTarget()){return nk(e,this.machineRuntime)}pluginLifecycleSupportNeedsReload(e,t){let n=nk(t,e),r=this.pluginLifecycleSupport(t);return rk(n)!==rk(r)}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}showSavedMessage(){this.savedMessage=`Config saved.`,this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage===`Config saved.`&&(this.savedMessage=``),this.savedMessageTimer=void 0},3e3)}static{this.styles=h`
5234
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await XO({loadConfig:()=>xo.config(),loadPlugins:()=>Co.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;this.accessLoading=!0,this.accessError=``;try{let n=await xo.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 ${nk(e)}: ${sk(dk(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;this.sessiondLoading=!0,this.sessiondError=``;try{let n=await xo.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 ${nk(e)}: ${sk(dk(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq;this.pluginLoading=!0,this.pluginError=``;try{let n=this.pluginLifecycleSupport(e);if(ak(n)){try{let r=await xo.config(e.id);if(!this.isCurrentPluginLoad(t,e))return;this.selectedPluginConfigResponse=r,this.selectedPluginsResponse=void 0,this.pluginError=n.message??`Plugin lifecycle diagnostics are not available on ${nk(e)}.`}catch(r){if(!this.isCurrentPluginLoad(t,e))return;this.pluginError=`Failed to load PI WEB plugin config from ${nk(e)}: ${sk(dk(r),e)}; ${n.message??`plugin lifecycle diagnostics are unsupported`}`}return}let[r,i]=await Promise.allSettled([xo.config(e.id),Co.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let a=[];r.status===`fulfilled`?this.selectedPluginConfigResponse=r.value:a.push(`config: ${sk(dk(r.reason),e)}`),i.status===`fulfilled`?this.selectedPluginsResponse=i.value:a.push(`PI WEB plugins: ${sk(dk(i.reason),e)}`),this.pluginError=a.length===0?``:`Failed to load PI WEB plugin settings from ${nk(e)}: ${a.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 ZO(e,e=>Do.packages(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.pluginLifecycleSupport(n);if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${nk(n)}. Reload before changing plugin enablement.`;return}let i=ck(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await xo.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=lk(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t;if(ak(r)?(this.selectedPluginsResponse=void 0,t=r.message??`Plugin lifecycle diagnostics are not available on ${nk(n)}.`):t=await this.refreshPluginsForTarget(n),!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEB plugin config on ${nk(n)}: ${sk(dk(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await xo.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${dk(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget();this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await xo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=$O(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 ${nk(t)}: ${sk(dk(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget();this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await xo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=lO(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${nk(t)}: ${sk(dk(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>Do.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>Do.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,()=>Do.update(e,t.id))}async runPiPackageMutation(e,t,n,r){if(this.saving)throw Error(`A settings operation is already running.`);let i=++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(i,n))return;this.packagesResponse={packages:e.packages};let t=hO(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(i,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=EO(e.action,n)}catch(e){throw this.isCurrentPackageMutation(i,n)&&(this.packageError=`Failed to ${t} on ${mO(n)}: ${DO(dk(e),n)}`),e}finally{this.packageMutationSeq===i&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Co.plugins();return}catch(e){return`Failed to refresh gateway PI WEB plugins: ${dk(e)}`}}async refreshPluginsForTarget(e){try{let t=await Co.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=void 0),`Config saved, but failed to refresh PI WEB plugins from ${nk(e)}: ${sk(dk(t),e)}`}}settingsTarget(){return tk(this.machine)}packageTarget(){return this.settingsTarget()}pluginLifecycleSupport(e=this.settingsTarget()){return rk(e,this.machineRuntime)}pluginLifecycleSupportNeedsReload(e,t){let n=rk(t,e),r=this.pluginLifecycleSupport(t);return ik(n)!==ik(r)}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}showSavedMessage(){this.savedMessage=`Config saved.`,this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage===`Config saved.`&&(this.savedMessage=``),this.savedMessageTimer=void 0},3e3)}static{this.styles=h`
5213
5235
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
5214
5236
  modal-surface { --modal-surface-backdrop-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)); --modal-surface-width: min(980px, 100%); --modal-surface-max-height: min(760px, 100%); --modal-surface-min-height: min(620px, 100%); --modal-surface-radius: 14px; }
5215
5237
  .settings-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
@@ -5234,7 +5256,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5234
5256
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
5235
5257
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
5236
5258
  }
5237
- `}};H([b({attribute:!1})],X.prototype,`section`,void 0),H([b({attribute:!1})],X.prototype,`actions`,void 0),H([b({attribute:!1})],X.prototype,`machine`,void 0),H([b({attribute:!1})],X.prototype,`machineRuntime`,void 0),H([b({attribute:!1})],X.prototype,`machines`,void 0),H([b({attribute:!1})],X.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],X.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],X.prototype,`onRenameMachine`,void 0),H([b({attribute:!1})],X.prototype,`onRemoveMachine`,void 0),H([b({attribute:!1})],X.prototype,`themes`,void 0),H([b({attribute:!1})],X.prototype,`selectedThemeId`,void 0),H([b({attribute:!1})],X.prototype,`activeThemeId`,void 0),H([b({type:Boolean})],X.prototype,`followSystemTheme`,void 0),H([b({attribute:!1})],X.prototype,`onSelectTheme`,void 0),H([b({attribute:!1})],X.prototype,`onToggleFollowSystem`,void 0),H([b({attribute:!1})],X.prototype,`fleetReport`,void 0),H([b({type:Boolean})],X.prototype,`fleetLoading`,void 0),H([b({attribute:!1})],X.prototype,`fleetError`,void 0),H([b({attribute:!1})],X.prototype,`onRefreshFleet`,void 0),H([b({attribute:!1})],X.prototype,`onRunFleet`,void 0),H([b({attribute:!1})],X.prototype,`onNavigate`,void 0),H([b({attribute:!1})],X.prototype,`onClose`,void 0),H([b({attribute:!1})],X.prototype,`onConfigSaved`,void 0),H([b({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),H([x()],X.prototype,`configResponse`,void 0),H([x()],X.prototype,`accessConfigResponse`,void 0),H([x()],X.prototype,`sessiondConfigResponse`,void 0),H([x()],X.prototype,`pluginsResponse`,void 0),H([x()],X.prototype,`selectedPluginConfigResponse`,void 0),H([x()],X.prototype,`selectedPluginsResponse`,void 0),H([x()],X.prototype,`packagesResponse`,void 0),H([x()],X.prototype,`loading`,void 0),H([x()],X.prototype,`accessLoading`,void 0),H([x()],X.prototype,`sessiondLoading`,void 0),H([x()],X.prototype,`pluginLoading`,void 0),H([x()],X.prototype,`packageLoading`,void 0),H([x()],X.prototype,`saving`,void 0),H([x()],X.prototype,`packageOperation`,void 0),H([x()],X.prototype,`error`,void 0),H([x()],X.prototype,`accessError`,void 0),H([x()],X.prototype,`sessiondError`,void 0),H([x()],X.prototype,`pluginError`,void 0),H([x()],X.prototype,`packageError`,void 0),H([x()],X.prototype,`savedMessage`,void 0),H([x()],X.prototype,`packageMessage`,void 0),X=H([y(`settings-dialog`)],X);function uk(e){return e instanceof Error?e.message:String(e)}var dk=class extends v{constructor(...e){super(...e),this.tool=`core:workspace.files`,this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>void 0,this.workspaceHeaderEdges=new VC(()=>{this.requestUpdate()}),this.onWorkspaceHeaderScroll=()=>{this.workspaceHeaderEdges.refresh()}}updated(){this.workspaceHeaderEdges.observe(this.workspaceHeaderStripElement())}disconnectedCallback(){this.workspaceHeaderEdges.dispose(),super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:`Select a workspace`,body:`Choose a workspace to use its tools.`});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.find(e=>e.id===this.tool)??t[0];return g`
5259
+ `}};H([b({attribute:!1})],X.prototype,`section`,void 0),H([b({attribute:!1})],X.prototype,`actions`,void 0),H([b({attribute:!1})],X.prototype,`machine`,void 0),H([b({attribute:!1})],X.prototype,`machineRuntime`,void 0),H([b({attribute:!1})],X.prototype,`machines`,void 0),H([b({attribute:!1})],X.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],X.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],X.prototype,`onRenameMachine`,void 0),H([b({attribute:!1})],X.prototype,`onRemoveMachine`,void 0),H([b({attribute:!1})],X.prototype,`themes`,void 0),H([b({attribute:!1})],X.prototype,`selectedThemeId`,void 0),H([b({attribute:!1})],X.prototype,`activeThemeId`,void 0),H([b({type:Boolean})],X.prototype,`followSystemTheme`,void 0),H([b({attribute:!1})],X.prototype,`onSelectTheme`,void 0),H([b({attribute:!1})],X.prototype,`onToggleFollowSystem`,void 0),H([b({attribute:!1})],X.prototype,`fleetReport`,void 0),H([b({type:Boolean})],X.prototype,`fleetLoading`,void 0),H([b({attribute:!1})],X.prototype,`fleetError`,void 0),H([b({attribute:!1})],X.prototype,`onRefreshFleet`,void 0),H([b({attribute:!1})],X.prototype,`onRunFleet`,void 0),H([b({attribute:!1})],X.prototype,`onNavigate`,void 0),H([b({attribute:!1})],X.prototype,`onClose`,void 0),H([b({attribute:!1})],X.prototype,`onConfigSaved`,void 0),H([b({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),H([x()],X.prototype,`configResponse`,void 0),H([x()],X.prototype,`accessConfigResponse`,void 0),H([x()],X.prototype,`sessiondConfigResponse`,void 0),H([x()],X.prototype,`pluginsResponse`,void 0),H([x()],X.prototype,`selectedPluginConfigResponse`,void 0),H([x()],X.prototype,`selectedPluginsResponse`,void 0),H([x()],X.prototype,`packagesResponse`,void 0),H([x()],X.prototype,`loading`,void 0),H([x()],X.prototype,`accessLoading`,void 0),H([x()],X.prototype,`sessiondLoading`,void 0),H([x()],X.prototype,`pluginLoading`,void 0),H([x()],X.prototype,`packageLoading`,void 0),H([x()],X.prototype,`saving`,void 0),H([x()],X.prototype,`packageOperation`,void 0),H([x()],X.prototype,`error`,void 0),H([x()],X.prototype,`accessError`,void 0),H([x()],X.prototype,`sessiondError`,void 0),H([x()],X.prototype,`pluginError`,void 0),H([x()],X.prototype,`packageError`,void 0),H([x()],X.prototype,`savedMessage`,void 0),H([x()],X.prototype,`packageMessage`,void 0),X=H([y(`settings-dialog`)],X);function dk(e){return e instanceof Error?e.message:String(e)}var fk=class extends v{constructor(...e){super(...e),this.tool=`core:workspace.files`,this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>void 0,this.workspaceHeaderEdges=new HC(()=>{this.requestUpdate()}),this.onWorkspaceHeaderScroll=()=>{this.workspaceHeaderEdges.refresh()}}updated(){this.workspaceHeaderEdges.observe(this.workspaceHeaderStripElement())}disconnectedCallback(){this.workspaceHeaderEdges.dispose(),super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:`Select a workspace`,body:`Choose a workspace to use its tools.`});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.find(e=>e.id===this.tool)??t[0];return g`
5238
5260
  ${this.hideToolTabs?null:g`
5239
5261
  <header>
5240
5262
  <div class=${this.workspaceHeaderFrameClass()}>
@@ -5264,12 +5286,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5264
5286
  <h2>${e.title}</h2>
5265
5287
  ${e.body===void 0?null:g`<p>${e.body}</p>`}
5266
5288
  </section>
5267
- `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${zC(this.workspaceHeaderEdges.edges)}`}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=rg}};H([b({attribute:!1})],dk.prototype,`workspace`,void 0),H([b({attribute:!1})],dk.prototype,`panelContext`,void 0),H([b({attribute:!1})],dk.prototype,`emptyState`,void 0),H([b()],dk.prototype,`tool`,void 0),H([b({attribute:!1})],dk.prototype,`panels`,void 0),H([b({type:Boolean})],dk.prototype,`hideToolTabs`,void 0),H([b({attribute:!1})],dk.prototype,`onSelectTool`,void 0),H([S(`.workspace-header-strip`)],dk.prototype,`workspaceHeaderStrip`,void 0),dk=H([y(`workspace-panel`)],dk);var Z=class extends v{constructor(...e){super(...e),this.machines=[],this.isWorking=!1,this.emphasizeSession=!1,this.renamingSession=!1,this.renameSeed=``,this.renameInputSeeded=!1,this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState();let e=this.renderRoot.querySelector(`.context-session-input`);e!==null&&!this.renameInputSeeded?(this.renameInputSeeded=!0,e.select()):e===null&&(this.renameInputSeeded=!1)}render(){return this.emphasizeSession&&this.session!==void 0?this.renderSessionLed():this.renderLocationTrail()}renderSessionLed(){let e=yk(this.workspace,this.project,this.machine,this.machines),t=xk(this.session);return g`
5289
+ `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${BC(this.workspaceHeaderEdges.edges)}`}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=rg}};H([b({attribute:!1})],fk.prototype,`workspace`,void 0),H([b({attribute:!1})],fk.prototype,`panelContext`,void 0),H([b({attribute:!1})],fk.prototype,`emptyState`,void 0),H([b()],fk.prototype,`tool`,void 0),H([b({attribute:!1})],fk.prototype,`panels`,void 0),H([b({type:Boolean})],fk.prototype,`hideToolTabs`,void 0),H([b({attribute:!1})],fk.prototype,`onSelectTool`,void 0),H([S(`.workspace-header-strip`)],fk.prototype,`workspaceHeaderStrip`,void 0),fk=H([y(`workspace-panel`)],fk);var Z=class extends v{constructor(...e){super(...e),this.machines=[],this.isWorking=!1,this.emphasizeSession=!1,this.renamingSession=!1,this.renameSeed=``,this.renameInputSeeded=!1,this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState();let e=this.renderRoot.querySelector(`.context-session-input`);e!==null&&!this.renameInputSeeded?(this.renameInputSeeded=!0,e.select()):e===null&&(this.renameInputSeeded=!1)}render(){return this.emphasizeSession&&this.session!==void 0?this.renderSessionLed():this.renderLocationTrail()}renderSessionLed(){let e=bk(this.workspace,this.project,this.machine,this.machines),t=Sk(this.session);return g`
5268
5290
  <nav class=${this.contextBarClass()} aria-label="Current session">
5269
5291
  <button
5270
5292
  type="button"
5271
5293
  class="context-breadcrumb"
5272
- title=${bk(this.workspace,this.project)}
5294
+ title=${xk(this.workspace,this.project)}
5273
5295
  aria-label=${`Location: ${e}. Open navigation.`}
5274
5296
  @click=${()=>{this.onOpenSection?.(this.breadcrumbSection())}}
5275
5297
  >${e}</button>
@@ -5304,7 +5326,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5304
5326
  </span>`:g`<button
5305
5327
  type="button"
5306
5328
  class="context-session-title"
5307
- title=${Sk(this.session)}
5329
+ title=${Ck(this.session)}
5308
5330
  aria-label=${`Session: ${t}. Open session selection.`}
5309
5331
  @click=${()=>{this.openSessions()}}
5310
5332
  >${t}</button>`}
@@ -5323,33 +5345,33 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5323
5345
  >✎</button>`}
5324
5346
  ${this.hasContextActions()?g`<div class="context-actions inline">${this.renderQuickSwitchButton()}${this.renderToolsButton()}${this.renderActionsButton()}${this.refreshControl}</div>`:null}
5325
5347
  </nav>
5326
- `}onRenameKeydown(e){if(e.key===`Escape`){e.preventDefault(),this.renamingSession=!1;return}e.key===`Enter`&&(e.preventDefault(),this.commitRename())}commitRename(){let e=(this.renderRoot.querySelector(`.context-session-input`)?.value??``).trim();this.renamingSession=!1,!(e===``||e===this.renameSeed||e===this.session?.name)&&this.onRenameSession?.(e)}breadcrumbSection(){return this.workspace===void 0?this.project===void 0&&fk(this.machines)?`machines`:`projects`:`workspaces`}renderLocationTrail(){let e=fk(this.machines),t=pk(this.machine),n=hk(this.project),r=_k(this.workspace),i=xk(this.session),a=this.session!==void 0;return g`
5348
+ `}onRenameKeydown(e){if(e.key===`Escape`){e.preventDefault(),this.renamingSession=!1;return}e.key===`Enter`&&(e.preventDefault(),this.commitRename())}commitRename(){let e=(this.renderRoot.querySelector(`.context-session-input`)?.value??``).trim();this.renamingSession=!1,!(e===``||e===this.renameSeed||e===this.session?.name)&&this.onRenameSession?.(e)}breadcrumbSection(){return this.workspace===void 0?this.project===void 0&&pk(this.machines)?`machines`:`projects`:`workspaces`}renderLocationTrail(){let e=pk(this.machines),t=mk(this.machine),n=gk(this.project),r=vk(this.workspace),i=Sk(this.session),a=this.session!==void 0;return g`
5327
5349
  <nav class=${this.contextBarClass()} aria-label="Current location">
5328
5350
  <span class="context-bar-label">Location</span>
5329
5351
  <ol class="context-items" @scroll=${this.onContextScroll}>
5330
5352
  ${e?g`
5331
5353
  <li class="context-item">
5332
- <button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${mk(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
5354
+ <button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${hk(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
5333
5355
  <span class="context-kind">Machine</span>
5334
5356
  <span class="context-value">${t}</span>
5335
5357
  </button>
5336
5358
  </li>
5337
5359
  `:null}
5338
5360
  <li class="context-item">
5339
- <button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${gk(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
5361
+ <button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${_k(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
5340
5362
  <span class="context-kind">Project</span>
5341
5363
  <span class="context-value">${n}</span>
5342
5364
  </button>
5343
5365
  </li>
5344
5366
  <li class="context-item">
5345
- <button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${vk(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
5367
+ <button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${yk(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
5346
5368
  <span class="context-kind">Workspace</span>
5347
5369
  <span class="context-value">${r}</span>
5348
5370
  </button>
5349
5371
  </li>
5350
5372
  ${a?g`
5351
5373
  <li class="context-item">
5352
- <button type="button" class="context-chip" title=${Sk(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.openSessions()}}>
5374
+ <button type="button" class="context-chip" title=${Ck(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.openSessions()}}>
5353
5375
  <span class="context-kind">Session</span>
5354
5376
  <span class="context-value session-value">${i}</span>
5355
5377
  </button>
@@ -5484,7 +5506,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5484
5506
  The row scrolls, so the extra width costs the others nothing. */
5485
5507
  .context-value.session-value { max-width: min(70vw, 32ch); }
5486
5508
  button { cursor: pointer; }
5487
- `}};H([b({attribute:!1})],Z.prototype,`machines`,void 0),H([b({attribute:!1})],Z.prototype,`machine`,void 0),H([b({attribute:!1})],Z.prototype,`project`,void 0),H([b({attribute:!1})],Z.prototype,`workspace`,void 0),H([b({attribute:!1})],Z.prototype,`session`,void 0),H([b({attribute:!1})],Z.prototype,`refreshControl`,void 0),H([b({attribute:!1})],Z.prototype,`onOpenSection`,void 0),H([b({attribute:!1})],Z.prototype,`onShowActions`,void 0),H([b({attribute:!1})],Z.prototype,`onQuickSwitch`,void 0),H([b({attribute:!1})],Z.prototype,`onOpenTools`,void 0),H([b({attribute:!1})],Z.prototype,`onRenameSession`,void 0),H([b({type:Boolean})],Z.prototype,`isWorking`,void 0),H([b({type:Boolean})],Z.prototype,`emphasizeSession`,void 0),H([S(`.context-items`)],Z.prototype,`contextItems`,void 0),H([x()],Z.prototype,`renamingSession`,void 0),H([x()],Z.prototype,`renameSeed`,void 0),H([x()],Z.prototype,`canScrollLeft`,void 0),H([x()],Z.prototype,`canScrollRight`,void 0),Z=H([y(`app-context-bar`)],Z);function fk(e){return e.length>0}function pk(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function mk(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function hk(e){return e?.name??`No project`}function gk(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function _k(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``}`}function vk(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function yk(e,t,n,r){let i=fk(r)&&n!==void 0?`${n.name} / `:``;return e===void 0?t===void 0?i===``?`No workspace`:i.replace(/ \/ $/u,``):`${i}${t.name}`:`${i}${e.isMain&&t!==void 0?t.name:e.label}`}function bk(e,t){return e===void 0?t===void 0?`No workspace selected`:t.path:e.path}function xk(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`:zx(e.id)}function Sk(e){return e===void 0?`No session selected`:e.path}var Ck=class extends v{constructor(...e){super(...e),this.tabs=[]}render(){return g`
5509
+ `}};H([b({attribute:!1})],Z.prototype,`machines`,void 0),H([b({attribute:!1})],Z.prototype,`machine`,void 0),H([b({attribute:!1})],Z.prototype,`project`,void 0),H([b({attribute:!1})],Z.prototype,`workspace`,void 0),H([b({attribute:!1})],Z.prototype,`session`,void 0),H([b({attribute:!1})],Z.prototype,`refreshControl`,void 0),H([b({attribute:!1})],Z.prototype,`onOpenSection`,void 0),H([b({attribute:!1})],Z.prototype,`onShowActions`,void 0),H([b({attribute:!1})],Z.prototype,`onQuickSwitch`,void 0),H([b({attribute:!1})],Z.prototype,`onOpenTools`,void 0),H([b({attribute:!1})],Z.prototype,`onRenameSession`,void 0),H([b({type:Boolean})],Z.prototype,`isWorking`,void 0),H([b({type:Boolean})],Z.prototype,`emphasizeSession`,void 0),H([S(`.context-items`)],Z.prototype,`contextItems`,void 0),H([x()],Z.prototype,`renamingSession`,void 0),H([x()],Z.prototype,`renameSeed`,void 0),H([x()],Z.prototype,`canScrollLeft`,void 0),H([x()],Z.prototype,`canScrollRight`,void 0),Z=H([y(`app-context-bar`)],Z);function pk(e){return e.length>0}function mk(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function hk(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function gk(e){return e?.name??`No project`}function _k(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function vk(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``}`}function yk(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function bk(e,t,n,r){let i=pk(r)&&n!==void 0?`${n.name} / `:``;return e===void 0?t===void 0?i===``?`No workspace`:i.replace(/ \/ $/u,``):`${i}${t.name}`:`${i}${e.isMain&&t!==void 0?t.name:e.label}`}function xk(e,t){return e===void 0?t===void 0?`No workspace selected`:t.path:e.path}function Sk(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?`No session`:zx(e.id)}function Ck(e){return e===void 0?`No session selected`:e.path}var wk=class extends v{constructor(...e){super(...e),this.tabs=[]}render(){return g`
5488
5510
  <modal-surface .onClose=${()=>this.onClose?.()} .label=${`Views`} .initialFocus=${`button`}>
5489
5511
  <header><h2>Go to</h2></header>
5490
5512
  <div class="body">
@@ -5523,7 +5545,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5523
5545
  .tool-badge { min-width: 20px; border-radius: var(--pi-radius-pill); background: var(--pi-surface-hover); color: var(--pi-text-secondary); padding: 1px var(--pi-space-4); font-size: var(--pi-text-xs); text-align: center; }
5524
5546
  .tool-badge.unread { background: var(--pi-selection-bg); color: var(--pi-accent); }
5525
5547
  .tool-check { color: var(--pi-accent); }
5526
- `}};H([b({attribute:!1})],Ck.prototype,`tabs`,void 0),H([b({attribute:!1})],Ck.prototype,`selectedView`,void 0),H([b({attribute:!1})],Ck.prototype,`onSelect`,void 0),H([b({attribute:!1})],Ck.prototype,`onClose`,void 0),Ck=H([y(`app-mobile-tool-sheet`)],Ck);var wk=`PI WEB`;function Tk(e){let t=e?.label.trim();if(!(t===void 0||t===``))return t.split(`/`).filter(e=>e!==``).pop()??t}function Ek(e){if(e.mainView===`chat`&&e.selectedSession!==void 0){let t=Bx(e.selectedSession).trim();if(t!==``)return t}let t=Tk(e.selectedWorkspace);if(t!==void 0)return t;let n=e.selectedProject?.name.trim();if(n!==void 0&&n!==``)return n;let r=e.selectedMachine;if(r!==void 0&&r.kind!==`local`){let e=r.name.trim();if(e!==``)return e}return wk}function Dk(e,t=40){let n=Ek(e);return n.length<=t?n:`${n.slice(0,t-1).trimEnd()}…`}var Ok=class extends v{constructor(...e){super(...e),this.machines=[]}render(){return g`
5548
+ `}};H([b({attribute:!1})],wk.prototype,`tabs`,void 0),H([b({attribute:!1})],wk.prototype,`selectedView`,void 0),H([b({attribute:!1})],wk.prototype,`onSelect`,void 0),H([b({attribute:!1})],wk.prototype,`onClose`,void 0),wk=H([y(`app-mobile-tool-sheet`)],wk);var Tk=`PI WEB`;function Ek(e){let t=e?.label.trim();if(!(t===void 0||t===``))return t.split(`/`).filter(e=>e!==``).pop()??t}function Dk(e){if(e.mainView===`chat`&&e.selectedSession!==void 0){let t=Bx(e.selectedSession).trim();if(t!==``)return t}let t=Ek(e.selectedWorkspace);if(t!==void 0)return t;let n=e.selectedProject?.name.trim();if(n!==void 0&&n!==``)return n;let r=e.selectedMachine;if(r!==void 0&&r.kind!==`local`){let e=r.name.trim();if(e!==``)return e}return Tk}function Ok(e,t=40){let n=Dk(e);return n.length<=t?n:`${n.slice(0,t-1).trimEnd()}…`}var kk=class extends v{constructor(...e){super(...e),this.machines=[]}render(){return g`
5527
5549
  <nav aria-label="Current context">
5528
5550
  ${this.machines.length>0?this.renderStep(`machines`,`Machine`,this.selectedMachine?.name,this.onAddMachine,`Add machine`):_}
5529
5551
  ${this.renderStep(`projects`,`Project`,this.selectedProject?.name,this.onAddProject,`Add project`)}
@@ -5575,12 +5597,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5575
5597
  .step.open .add { border-left-color: color-mix(in srgb, var(--pi-accent) 40%, var(--pi-border)); }
5576
5598
  @media (pointer: coarse) { .add { width: 40px; } }
5577
5599
  .add:hover { color: var(--pi-text); }
5578
- `}};H([b({attribute:!1})],Ok.prototype,`machines`,void 0),H([b({attribute:!1})],Ok.prototype,`selectedMachine`,void 0),H([b({attribute:!1})],Ok.prototype,`selectedProject`,void 0),H([b({attribute:!1})],Ok.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],Ok.prototype,`openSection`,void 0),H([b({attribute:!1})],Ok.prototype,`onOpenSection`,void 0),H([b({attribute:!1})],Ok.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],Ok.prototype,`onAddProject`,void 0),Ok=H([y(`app-context-switcher`)],Ok);var kk=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},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=Ak(e,this.statuses),n=e.name;return g`
5600
+ `}};H([b({attribute:!1})],kk.prototype,`machines`,void 0),H([b({attribute:!1})],kk.prototype,`selectedMachine`,void 0),H([b({attribute:!1})],kk.prototype,`selectedProject`,void 0),H([b({attribute:!1})],kk.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],kk.prototype,`openSection`,void 0),H([b({attribute:!1})],kk.prototype,`onOpenSection`,void 0),H([b({attribute:!1})],kk.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],kk.prototype,`onAddProject`,void 0),kk=H([y(`app-context-switcher`)],kk);var Ak=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},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=jk(e,this.statuses),n=e.name;return g`
5579
5601
  <div class="machine-switcher">
5580
5602
  <button
5581
5603
  type="button"
5582
5604
  class="machine-switcher-button"
5583
- title=${Mk(e)}
5605
+ title=${Nk(e)}
5584
5606
  aria-label=${this.machineSwitcherAriaLabel(e)}
5585
5607
  aria-expanded=${String(this.open)}
5586
5608
  @click=${e=>{this.toggleMenu(e.currentTarget)}}
@@ -5591,7 +5613,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5591
5613
  <span class="machine-switcher-kicker">Machine</span>
5592
5614
  <span class="machine-switcher-label">${n}</span>
5593
5615
  </span>
5594
- <span class=${`machine-status ${t}`}>${jk(t)}</span>
5616
+ <span class=${`machine-status ${t}`}>${Mk(t)}</span>
5595
5617
  <span class="machine-chevron" aria-hidden="true">▾</span>
5596
5618
  </button>
5597
5619
  ${this.open?g`
@@ -5600,17 +5622,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5600
5622
  </div>
5601
5623
  `:null}
5602
5624
  </div>
5603
- `}renderMachineOption(e){let t=this.selected?.id===e.id,n=Ak(e,this.statuses),r=yx(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
5625
+ `}renderMachineOption(e){let t=this.selected?.id===e.id,n=jk(e,this.statuses),r=yx(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
5604
5626
  <div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
5605
5627
  <button
5606
5628
  type="button"
5607
5629
  class="machine-option-main"
5608
- title=${Mk(e)}
5630
+ title=${Nk(e)}
5609
5631
  data-machine-id=${e.id}
5610
5632
  @click=${()=>{this.select(e)}}
5611
5633
  @keydown=${e=>{this.handleMachineOptionKeydown(e)}}
5612
5634
  >
5613
- <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span><span class=${`machine-option-status ${n}`}><span class="dot" aria-hidden="true"></span>${jk(n)}</span></span>
5635
+ <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span><span class=${`machine-option-status ${n}`}><span class="dot" aria-hidden="true"></span>${Mk(n)}</span></span>
5614
5636
  <small>${e.kind===`local`?`Local Pi Web`:e.baseUrl??`Remote Pi Web`}</small>
5615
5637
  </button>
5616
5638
  ${r?g`
@@ -5631,7 +5653,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5631
5653
  </div>
5632
5654
  `:null}
5633
5655
  </div>
5634
- `}renderActivity(e){let t=this.statusSnapshots[e.id]?.machine,n=Ak(e,this.statuses),r=n===`offline`||n===`error`?void 0:nx(t),i=rx(t)?`Unread sessions on this machine`:void 0;return tx(r,r===`terminal`?`Machine terminal active`:`Machine active`,i)}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=Nk(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=Nk(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=Zb(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`
5656
+ `}renderActivity(e){let t=this.statusSnapshots[e.id]?.machine,n=jk(e,this.statuses),r=n===`offline`||n===`error`?void 0:nx(t),i=rx(t)?`Unread sessions on this machine`:void 0;return tx(r,r===`terminal`?`Machine terminal active`:`Machine active`,i)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`Machine: ${e.name}. Switch machine.`}switcherButton(){return this.renderRoot.querySelector(`.machine-switcher-button`)}handleSwitcherButtonKeydown(e){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key===`Escape`&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key===`ArrowUp`){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key===`ArrowDown`){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key===`Home`){this.focusIndexedMachineOption(0,e);return}if(e.key===`End`){this.focusIndexedMachineOption(-1,e);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key===`ArrowLeft`||e.key===`Escape`)&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=Pk(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){let e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=Pk(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){let e=this.renderRoot.querySelector(`.machine-option.selected .machine-option-main`),t=this.machineOptionButtons()[0],n=e??t;return n===void 0?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}focusRelativeMachineOption(e,t,n){n.preventDefault(),n.stopPropagation();let r=this.machineOptionButtons();if(r.length===0||!(e instanceof HTMLElement))return;let i=r.indexOf(e);i<0||this.focusMachineOptionAt(i+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){let t=this.machineOptionButtons(),n=t[Math.min(Math.max(e,0),t.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(`.machine-option-main`))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=Zb(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`
5635
5657
  :host { min-width: 0; display: block; }
5636
5658
  /* A display rule on :host outranks the HTML hidden attribute, so an element
5637
5659
  rendered with the hidden attribute stays on screen unless this says so.
@@ -5683,7 +5705,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5683
5705
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
5684
5706
  .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); }
5685
5707
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
5686
- `}};H([b({attribute:!1})],kk.prototype,`machines`,void 0),H([b({attribute:!1})],kk.prototype,`selected`,void 0),H([b({attribute:!1})],kk.prototype,`statuses`,void 0),H([b({attribute:!1})],kk.prototype,`statusSnapshots`,void 0),H([b({attribute:!1})],kk.prototype,`onSelect`,void 0),H([b({attribute:!1})],kk.prototype,`onRemove`,void 0),H([b({attribute:!1})],kk.prototype,`onFocusNextSection`,void 0),H([b({attribute:!1})],kk.prototype,`onCancelKeyboardNavigation`,void 0),H([x()],kk.prototype,`open`,void 0),H([x()],kk.prototype,`menuStyle`,void 0),H([x()],kk.prototype,`openActionsMachineId`,void 0),H([x()],kk.prototype,`actionMenuStyle`,void 0),kk=H([y(`machine-switcher`)],kk);function Ak(e,t){return t[e.id]?.status??e.status??`unknown`}function jk(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function Mk(e){return e.baseUrl??e.name}function Nk(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: ${Pk(t.bottom)};`,`left: ${Pk(r)};`,`width: ${Pk(n)};`,`max-height: ${Pk(i)};`].join(` `)}function Pk(e){return`${String(Math.round(e))}px`}var Q=class extends v{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineStatusSnapshots={},this.projects=[],this.workspaces=[],this.sessions=[],this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,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.goals=[],this.goalsLoading=!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)}}headerName(){return Ek({mainView:this.selectedSession===void 0?`navigation`:`chat`,selectedMachine:this.selectedMachine,selectedProject:this.selectedProject,selectedWorkspace:this.selectedWorkspace,selectedSession:this.selectedSession})}render(){if(this.compact)return this.renderCompact();let e=this.compactVisibleSection();return g`
5708
+ `}};H([b({attribute:!1})],Ak.prototype,`machines`,void 0),H([b({attribute:!1})],Ak.prototype,`selected`,void 0),H([b({attribute:!1})],Ak.prototype,`statuses`,void 0),H([b({attribute:!1})],Ak.prototype,`statusSnapshots`,void 0),H([b({attribute:!1})],Ak.prototype,`onSelect`,void 0),H([b({attribute:!1})],Ak.prototype,`onRemove`,void 0),H([b({attribute:!1})],Ak.prototype,`onFocusNextSection`,void 0),H([b({attribute:!1})],Ak.prototype,`onCancelKeyboardNavigation`,void 0),H([x()],Ak.prototype,`open`,void 0),H([x()],Ak.prototype,`menuStyle`,void 0),H([x()],Ak.prototype,`openActionsMachineId`,void 0),H([x()],Ak.prototype,`actionMenuStyle`,void 0),Ak=H([y(`machine-switcher`)],Ak);function jk(e,t){return t[e.id]?.status??e.status??`unknown`}function Mk(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function Nk(e){return e.baseUrl??e.name}function Pk(e){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let t=e.getBoundingClientRect(),n=Math.min(280,Math.max(0,window.innerWidth-16)),r=Math.min(Math.max(8,t.left),Math.max(8,window.innerWidth-8-n)),i=Math.max(0,window.innerHeight-t.bottom-8);return[`top: ${Fk(t.bottom)};`,`left: ${Fk(r)};`,`width: ${Fk(n)};`,`max-height: ${Fk(i)};`].join(` `)}function Fk(e){return`${String(Math.round(e))}px`}var Q=class extends v{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineStatusSnapshots={},this.projects=[],this.workspaces=[],this.sessions=[],this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,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.goals=[],this.goalsLoading=!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)}}headerName(){return Dk({mainView:this.selectedSession===void 0?`navigation`:`chat`,selectedMachine:this.selectedMachine,selectedProject:this.selectedProject,selectedWorkspace:this.selectedWorkspace,selectedSession:this.selectedSession})}render(){if(this.compact)return this.renderCompact();let e=this.compactVisibleSection();return g`
5687
5709
  <header>
5688
5710
  <strong title=${this.headerName()}>${this.headerName()}</strong>
5689
5711
  <div class="header-actions">
@@ -5709,7 +5731,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5709
5731
  ${e===`sessions`?this.renderGoalPanel():null}
5710
5732
  `}renderCompact(){return g`
5711
5733
  <div class="compact-shell">
5712
- ${Fk(this.machines)?g`
5734
+ ${Ik(this.machines)?g`
5713
5735
  <machine-switcher
5714
5736
  hidden
5715
5737
  .machines=${this.machines}
@@ -5741,7 +5763,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5741
5763
  ${this.renderWorkspaceList(!1,e!==`workspaces`)}
5742
5764
  ${this.renderSessionList(!1,e!==`sessions`)}
5743
5765
  ${e===`sessions`?this.renderGoalPanel():null}
5744
- `}openSection(e){e===`machines`?this.onToggleMachines?.():e===`projects`?this.onToggleProjects?.():e===`workspaces`?this.onToggleWorkspaces?.():this.onToggleSessions?.()}compactVisibleSection(){return Fk(this.machines)&&!this.machinesCollapsed?`machines`:this.projectsCollapsed?this.workspacesCollapsed?!this.sessionsCollapsed||this.selectedWorkspace!==void 0?`sessions`:this.selectedProject===void 0?`projects`:`workspaces`:`workspaces`:`projects`}renderMachineList(e,t=!1){return Fk(this.machines)?g`
5766
+ `}openSection(e){e===`machines`?this.onToggleMachines?.():e===`projects`?this.onToggleProjects?.():e===`workspaces`?this.onToggleWorkspaces?.():this.onToggleSessions?.()}compactVisibleSection(){return Ik(this.machines)&&!this.machinesCollapsed?`machines`:this.projectsCollapsed?this.workspacesCollapsed?!this.sessionsCollapsed||this.selectedWorkspace!==void 0?`sessions`:this.selectedProject===void 0?`projects`:`workspaces`:`workspaces`:`projects`}renderMachineList(e,t=!1){return Ik(this.machines)?g`
5745
5767
  <machine-list
5746
5768
  ?hidden=${t}
5747
5769
  .machines=${this.machines}
@@ -5840,7 +5862,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5840
5862
  .onFocusNextSection=${()=>{this.focusNextFrom(`sessions`)}}
5841
5863
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
5842
5864
  ></session-list>
5843
- `}selectedMachineStatusSnapshot(){return this.machineStatusSnapshots[L({selectedMachine:this.selectedMachine})]}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}runMaybeAsync(e){e?.()instanceof Promise}focusPreviousFrom(e){let t=Ik(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Lk(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
5865
+ `}selectedMachineStatusSnapshot(){return this.machineStatusSnapshots[L({selectedMachine:this.selectedMachine})]}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}runMaybeAsync(e){e?.()instanceof Promise}focusPreviousFrom(e){let t=Lk(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Rk(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
5844
5866
  /* Shell styles do not cross a shadow boundary, so the tap-highlight
5845
5867
  suppression is repeated for components that define their own. */
5846
5868
  button, [role="button"], a, summary, label, input { -webkit-tap-highlight-color: transparent; }
@@ -5871,7 +5893,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5871
5893
  task list cannot push the sessions it belongs to off-screen. */
5872
5894
  goal-panel { flex: 0 1 auto; min-height: 0; max-height: var(--pi-nav-goals-max-height, 26vh); overflow: auto; border-top: 1px solid var(--pi-border-muted); }
5873
5895
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
5874
- `}};H([b({attribute:!1})],Q.prototype,`machines`,void 0),H([b({attribute:!1})],Q.prototype,`selectedMachine`,void 0),H([b({attribute:!1})],Q.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],Q.prototype,`machineStatusSnapshots`,void 0),H([b({attribute:!1})],Q.prototype,`projects`,void 0),H([b({attribute:!1})],Q.prototype,`selectedProject`,void 0),H([b({attribute:!1})],Q.prototype,`workspaces`,void 0),H([b({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`sessions`,void 0),H([b({attribute:!1})],Q.prototype,`selectedSession`,void 0),H([b({attribute:!1})],Q.prototype,`sessionActivities`,void 0),H([b({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),H([b({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),H([b({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),H([b({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),H([b({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),H([b({attribute:!1})],Q.prototype,`refreshControl`,void 0),H([b({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),H([b({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),H([b({type:Number})],Q.prototype,`startingSessionCount`,void 0),H([b({type:Boolean})],Q.prototype,`canStartSession`,void 0),H([b({attribute:!1})],Q.prototype,`onShowActions`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenSettings`,void 0),H([b({attribute:!1})],Q.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenSessionTree`,void 0),H([b({attribute:!1})],Q.prototype,`onRefreshMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onRenameMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onQuickSwitch`,void 0),H([b({attribute:!1})],Q.prototype,`onAddProject`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectProject`,void 0),H([b({attribute:!1})],Q.prototype,`onCloseProject`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`onStartSession`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectSession`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),H([b({attribute:!1})],Q.prototype,`onRenameSession`,void 0),H([b({attribute:!1})],Q.prototype,`goals`,void 0),H([b({type:Boolean})],Q.prototype,`goalsLoading`,void 0),H([b({attribute:!1})],Q.prototype,`onRefreshGoals`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveGoal`,void 0),H([b({attribute:!1})],Q.prototype,`onRunGoalCommand`,void 0),H([b({attribute:!1})],Q.prototype,`onMarkSessionRead`,void 0),H([b({attribute:!1})],Q.prototype,`onMarkSessionsRead`,void 0),H([b({attribute:!1})],Q.prototype,`onReloadSession`,void 0),H([b({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),H([b({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),H([S(`machine-list`)],Q.prototype,`machineList`,void 0),H([S(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),H([S(`project-list`)],Q.prototype,`projectList`,void 0),H([S(`workspace-list`)],Q.prototype,`workspaceList`,void 0),H([S(`session-list`)],Q.prototype,`sessionList`,void 0),Q=H([y(`app-navigation-panel`)],Q);function Fk(e){return e.length>0}function Ik(e,t){let n=Rk(t);return n[n.indexOf(e)-1]}function Lk(e,t){let n=Rk(t);return n[n.indexOf(e)+1]??`chat`}function Rk(e){return eb.filter(t=>t!==`machines`||Fk(e))}var zk=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),Bk=420,Vk=4,Hk=class extends v{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`
5896
+ `}};H([b({attribute:!1})],Q.prototype,`machines`,void 0),H([b({attribute:!1})],Q.prototype,`selectedMachine`,void 0),H([b({attribute:!1})],Q.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],Q.prototype,`machineStatusSnapshots`,void 0),H([b({attribute:!1})],Q.prototype,`projects`,void 0),H([b({attribute:!1})],Q.prototype,`selectedProject`,void 0),H([b({attribute:!1})],Q.prototype,`workspaces`,void 0),H([b({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`sessions`,void 0),H([b({attribute:!1})],Q.prototype,`selectedSession`,void 0),H([b({attribute:!1})],Q.prototype,`sessionActivities`,void 0),H([b({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),H([b({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),H([b({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),H([b({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),H([b({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),H([b({attribute:!1})],Q.prototype,`refreshControl`,void 0),H([b({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),H([b({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),H([b({type:Number})],Q.prototype,`startingSessionCount`,void 0),H([b({type:Boolean})],Q.prototype,`canStartSession`,void 0),H([b({attribute:!1})],Q.prototype,`onShowActions`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenSettings`,void 0),H([b({attribute:!1})],Q.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenSessionTree`,void 0),H([b({attribute:!1})],Q.prototype,`onRefreshMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onRenameMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onQuickSwitch`,void 0),H([b({attribute:!1})],Q.prototype,`onAddProject`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectProject`,void 0),H([b({attribute:!1})],Q.prototype,`onCloseProject`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`onStartSession`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectSession`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),H([b({attribute:!1})],Q.prototype,`onRenameSession`,void 0),H([b({attribute:!1})],Q.prototype,`goals`,void 0),H([b({type:Boolean})],Q.prototype,`goalsLoading`,void 0),H([b({attribute:!1})],Q.prototype,`onRefreshGoals`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveGoal`,void 0),H([b({attribute:!1})],Q.prototype,`onRunGoalCommand`,void 0),H([b({attribute:!1})],Q.prototype,`onMarkSessionRead`,void 0),H([b({attribute:!1})],Q.prototype,`onMarkSessionsRead`,void 0),H([b({attribute:!1})],Q.prototype,`onReloadSession`,void 0),H([b({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),H([b({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),H([S(`machine-list`)],Q.prototype,`machineList`,void 0),H([S(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),H([S(`project-list`)],Q.prototype,`projectList`,void 0),H([S(`workspace-list`)],Q.prototype,`workspaceList`,void 0),H([S(`session-list`)],Q.prototype,`sessionList`,void 0),Q=H([y(`app-navigation-panel`)],Q);function Ik(e){return e.length>0}function Lk(e,t){let n=zk(t);return n[n.indexOf(e)-1]}function Rk(e,t){let n=zk(t);return n[n.indexOf(e)+1]??`chat`}function zk(e){return eb.filter(t=>t!==`machines`||Ik(e))}var Bk=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),Vk=420,Hk=4,Uk=class extends v{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`
5875
5897
  ${this.renderResizeHandle()}
5876
5898
  <button
5877
5899
  type="button"
@@ -5901,7 +5923,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5901
5923
  @dblclick=${e=>{this.onResizeDoubleClick(e)}}
5902
5924
  @keydown=${e=>{this.onResizeKeyDown(e)}}
5903
5925
  ></div>
5904
- `}resizeAriaValueNow(){return this.panelWidth===void 0?_: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)<=Vk)&&(t.moved=!0,this.commitPanelWidth(gb(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||!zk.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=_b(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<=Bk){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 vb(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(vb(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=mb(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
5926
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?_: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)<=Hk)&&(t.moved=!0,this.commitPanelWidth(gb(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||!Bk.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=_b(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<=Vk){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 vb(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(vb(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=mb(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
5905
5927
  :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; }
5906
5928
  :host([side="navigation"]) { grid-column: 2; }
5907
5929
  :host([side="workspace"]) { grid-column: 4; }
@@ -5928,7 +5950,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5928
5950
  @media (max-width: 760px) {
5929
5951
  :host([side="navigation"]) { display: none; }
5930
5952
  }
5931
- `}};H([b({reflect:!0})],Hk.prototype,`side`,void 0),H([b({type:Boolean,reflect:!0})],Hk.prototype,`collapsed`,void 0),H([b({type:Boolean})],Hk.prototype,`resizable`,void 0),H([b({type:Number})],Hk.prototype,`panelWidth`,void 0),H([b({type:Number})],Hk.prototype,`minWidth`,void 0),H([b({type:Number})],Hk.prototype,`maxWidth`,void 0),H([b()],Hk.prototype,`controls`,void 0),H([b()],Hk.prototype,`resizeLabel`,void 0),H([b()],Hk.prototype,`expandLabel`,void 0),H([b()],Hk.prototype,`collapseLabel`,void 0),H([b({attribute:!1})],Hk.prototype,`onToggle`,void 0),H([b({attribute:!1})],Hk.prototype,`onResizeStart`,void 0),H([b({attribute:!1})],Hk.prototype,`onResize`,void 0),H([b({attribute:!1})],Hk.prototype,`onResizeEnd`,void 0),H([b({attribute:!1})],Hk.prototype,`onReset`,void 0),Hk=H([y(`app-panel-edge-control`)],Hk);var Uk=class extends v{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
5953
+ `}};H([b({reflect:!0})],Uk.prototype,`side`,void 0),H([b({type:Boolean,reflect:!0})],Uk.prototype,`collapsed`,void 0),H([b({type:Boolean})],Uk.prototype,`resizable`,void 0),H([b({type:Number})],Uk.prototype,`panelWidth`,void 0),H([b({type:Number})],Uk.prototype,`minWidth`,void 0),H([b({type:Number})],Uk.prototype,`maxWidth`,void 0),H([b()],Uk.prototype,`controls`,void 0),H([b()],Uk.prototype,`resizeLabel`,void 0),H([b()],Uk.prototype,`expandLabel`,void 0),H([b()],Uk.prototype,`collapseLabel`,void 0),H([b({attribute:!1})],Uk.prototype,`onToggle`,void 0),H([b({attribute:!1})],Uk.prototype,`onResizeStart`,void 0),H([b({attribute:!1})],Uk.prototype,`onResize`,void 0),H([b({attribute:!1})],Uk.prototype,`onResizeEnd`,void 0),H([b({attribute:!1})],Uk.prototype,`onReset`,void 0),Uk=H([y(`app-panel-edge-control`)],Uk);var Wk=class extends v{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
5932
5954
  <button
5933
5955
  class="app-refresh-button"
5934
5956
  title=${e}
@@ -5947,12 +5969,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5947
5969
  :host, :host * { -webkit-user-select: none; user-select: none; }
5948
5970
  .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; }
5949
5971
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
5950
- `}};H([b({attribute:!1})],Uk.prototype,`onReload`,void 0),Uk=H([y(`app-refresh-control`)],Uk);var Wk=`pi-web.pinnedSessions`;function Gk(e=Jk()){if(e===void 0)return new Set;try{let t=e.getItem(Wk);if(t===null||t===``)return new Set;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function Kk(e,t=Jk()){if(t!==void 0)try{t.setItem(Wk,JSON.stringify([...e]))}catch{}}function qk(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function Jk(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var Yk=new Set([`text`,`search`,`email`,`url`,`tel`,`password`,`number`,void 0]);function Xk(e){if(e===void 0)return!1;if(e.isContentEditable===!0)return!0;let t=e.tagName.toUpperCase();return t===`TEXTAREA`||t===`INPUT`&&Yk.has(e.type)}function Zk(e=document){let t=e.activeElement;t!==null&&Xk({tagName:t.tagName,...t instanceof HTMLInputElement?{type:t.type}:{},...t instanceof HTMLElement?{isContentEditable:t.isContentEditable}:{}})&&t instanceof HTMLElement&&t.blur()}function Qk(e,t){if(e===``)return null;let n=tA(e);return g`<div class=${`error${n===void 0?``:` transient`}`} role=${n===void 0?`alert`:`status`}>
5972
+ `}};H([b({attribute:!1})],Wk.prototype,`onReload`,void 0),Wk=H([y(`app-refresh-control`)],Wk);var Gk=`pi-web.pinnedSessions`;function Kk(e=Yk()){if(e===void 0)return new Set;try{let t=e.getItem(Gk);if(t===null||t===``)return new Set;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function qk(e,t=Yk()){if(t!==void 0)try{t.setItem(Gk,JSON.stringify([...e]))}catch{}}function Jk(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function Yk(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var Xk=new Set([`text`,`search`,`email`,`url`,`tel`,`password`,`number`,void 0]);function Zk(e){if(e===void 0)return!1;if(e.isContentEditable===!0)return!0;let t=e.tagName.toUpperCase();return t===`TEXTAREA`||t===`INPUT`&&Xk.has(e.type)}function Qk(e=document){let t=e.activeElement;t!==null&&Zk({tagName:t.tagName,...t instanceof HTMLInputElement?{type:t.type}:{},...t instanceof HTMLElement?{isContentEditable:t.isContentEditable}:{}})&&t instanceof HTMLElement&&t.blur()}function $k(e,t){if(e===``)return null;let n=nA(e);return g`<div class=${`error${n===void 0?``:` transient`}`} role=${n===void 0?`alert`:`status`}>
5951
5973
  <span class="error-text">${n??e}</span>
5952
5974
  <button type="button" class="error-dismiss" aria-label="Dismiss error" title="Dismiss error" @click=${()=>{t()}}>✕</button>
5953
- </div>`}function $k(e){return tA(e)!==void 0}var eA=6e3;function tA(e){if(/session daemon workspace authority unavailable: connect (enoent|econnrefused)/i.test(e)&&/sessiond\.sock/i.test(e))return`Reconnecting to the session daemon…`;if(/\boperation was aborted\b/i.test(e))return`Previous request was interrupted. Retry if the message did not finish.`;if(/remote machine request cancelled/i.test(e))return`Connection changed while the request was in flight. Retrying is usually enough.`;if(/failed to fetch|load failed|networkerror when attempting to fetch/i.test(e))return`Lost connection to PI WEB. Reconnecting…`}function nA(e,t){let n=[];for(let r of e){let e=t[r.id]?.deprecatedAgentInputs;e===void 0||e.length===0||n.push({machineId:r.id,machineName:r.name,inputs:e})}return n}function rA(e){let t=e.inputs.map(iA).join(`; `);return`${e.machineName}: ${t}. Support for deprecated agent configuration inputs will be removed in a future release.`}function iA(e){let t=e.source===`config`?`config key ${e.name}`:`environment variable ${e.name}`;return e.replacement===void 0?`${t} is deprecated and ignored; remove it, there is no replacement`:`${t} is deprecated; set ${e.replacement} instead`}function aA(e){return e.length===0?null:g`<div class="deprecation-notice" role="alert">
5954
- ${e.map(e=>g`<p class="deprecation-notice-text">${rA(e)}</p>`)}
5955
- </div>`}var oA=900*1e3,sA=4e3,cA=15e3;function lA(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.addEventListener==`function`&&typeof t.removeEventListener==`function`}var uA=750,dA=[1e3,3e3,8e3,15e3,3e4],fA={capture:!0},pA=`auto:on`,mA=`auto:off`,hA=`theme:`,gA=$s(`core:workspace.files`),_A=$s(`core:workspace.terminal`),vA=320,yA=2,bA=`(min-width: 1181px)`,$=class extends v{constructor(...e){super(...e),this.state=Hs(),this.sessionUnread=new Im({onChange:e=>{L(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.interruptedSessionIds=new Set,this.unreadSessionIds=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new up(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Cf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new pf,{notifications:this.notifications,onSelectedSessionIdle:()=>{this.workspaces.refreshWorkspaceGoals()},onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t),this.refreshSelfUpdate()},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(L(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.machineStatus=new xc(()=>this.state,e=>{this.setState(e)}),this.auth=new Ys(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new yp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new gp),this.projects=new Cc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new _c(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new Tc(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new pc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Up,this.realtime=new qd,this.machineRealtimeSockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Tp,this.terminalSelection=new Rp,this.appShell=new Ky(this),this.browserResume=new Yy({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new cb(this),this.panelResize=new pb(this),this.navigationSections=new sb(this,()=>this.state),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=xA(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=th()??Zm,this.activeThemeId=Xm,this.isRefreshingApp=!1,this.lastScheduledError=``,this.quickSwitcherOpen=!1,this.composerCollapsed=!1,this.mobileToolSheetOpen=!1,this.quickSwitcherLoading=!1,this.quickSwitcherSessions=[],this.pinnedSessionIds=Gk(),this.quickSwitcherWorkspaces=[],this.settingsSection=Fb(),this.fleetLoading=!1,this.fleetSectionShown=!1,this.shortcutConfig={},this.workspaceUploadDefaultFolder=xs(void 0),this.sessionWarningVisibility=Wm(),this.onPopState=()=>{if(this.modalLayerOpen()){this.closeModalLayer();return}this.currentRouteMatchesUrl()||this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.sessionUnread.refreshAll(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onBrowserOnline=()=>{this.realtime.reconnectNow(),this.sessions.reconnectSocketNow(),this.checkSocketLiveness()},this.onFocusIn=e=>{this.composerCollapsed=_m(e.composedPath())},this.onFocusOut=e=>{let t=e.relatedTarget;t!==null&&(this.composerCollapsed=_m(vm(t)))},this.onDocumentVisibilityChange=()=>{this.updateSubagentPolling(),document.visibilityState===`visible`&&this.refreshSubagents()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.isRenderedModalOpen()||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.selfUpdateCooldownUntil=0,this.onVisualViewportChange=()=>{let e=hm(window.innerHeight,window.visualViewport??void 0);this.style.setProperty(`--pi-app-keyboard-inset`,`${String(Math.round(e))}px`)},this.handleSendPrompt=(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i),this.handleStopActiveWork=()=>{this.sessions.stopActiveWork().then(e=>{this.restoreToComposer(e)})},this.handleClearServerQueue=e=>{this.restoreToComposer(e),this.sessions.clearServerQueue()},this.handleOpenSubagentRun=e=>{this.sessions.openSubagentRunOutput(e)},this.handleOpenBackgroundTask=e=>{e.hasOutput&&this.sessions.openBackgroundTaskOutput(e)},this.handleCloseActivityOutput=()=>{this.sessions.closeActivityOutput()},this.handleOpenSubagentSession=e=>{this.openSubagent(e)},this.handleRecallQueuedMessage=e=>{this.sessions.recallQueuedMessage(e).then(t=>{t&&this.restoreToComposer([e])})},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Ym(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleResendMessage=e=>{this.promptEditor?.restorePrompt(e)},this.handleSelectModel=()=>{this.openModelDialog()},this.handleToggleModelEnabled=async(e,t,n)=>{let r=await this.sessions.setModelEnabled(e,t,n),i=this.state.modelDialog;r===void 0||i===void 0||this.setState({modelDialog:{...i,catalog:r,options:this.modelDialogOptions(r.filter(e=>e.enabled))}})},this.handleSelectThinking=()=>{this.openThinkingDialog()}}currentRouteMatchesUrl(){let e=this.state,t=new URL(window.location.href),n=e=>{let n=t.searchParams.get(e);return n===null||n===``?void 0:n},r=e.selectedMachine===void 0?void 0:e.selectedMachine.id;return n(`machine`)===(r===`local`?void 0:r)&&n(`project`)===(e.selectedProject===void 0?void 0:e.selectedProject.id)&&n(`workspace`)===(e.selectedWorkspace===void 0?void 0:e.selectedWorkspace.id)&&n(`session`)===(e.selectedSession===void 0?void 0:e.selectedSession.id)}closeModalLayer(){if(this.mobileToolSheetOpen){this.mobileToolSheetOpen=!1;return}if(this.quickSwitcherOpen){this.quickSwitcherOpen=!1;return}let e=this.state;if(e.actionPaletteOpen){this.setState({actionPaletteOpen:!1});return}if(e.projectDialogOpen){this.setState({projectDialogOpen:!1});return}if(e.machineDialogOpen){this.setState({machineDialogOpen:!1});return}if(e.commandDialog!==void 0){this.sessions.cancelCommand();return}if(e.modelDialog!==void 0){this.setState({modelDialog:void 0});return}if(e.thinkingDialog!==void 0){this.setState({thinkingDialog:void 0});return}if(e.themeDialog!==void 0){this.setState({themeDialog:void 0});return}if(this.sessionCleanupDialog!==void 0){this.sessionCleanupDialog=void 0;return}}listenForFormFocus(e){let t=this.renderRoot;if(lA(t)){if(e===`add`){t.addEventListener(`focusin`,this.onFocusIn),t.addEventListener(`focusout`,this.onFocusOut);return}t.removeEventListener(`focusin`,this.onFocusIn),t.removeEventListener(`focusout`,this.onFocusOut)}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=TA(this.state),this.syncSelectedSessionReadState(),this.syncFleetOnSettingsSection(),this.syncDocumentTitle()}syncDocumentTitle(){let e=this.state,t=Dk({mainView:e.mainView,selectedMachine:e.selectedMachine,selectedProject:e.selectedProject,selectedWorkspace:e.selectedWorkspace,selectedSession:e.selectedSession});document.title!==t&&(document.title=t)}syncFleetOnSettingsSection(){let e=this.settingsSection===`machines`;e&&!this.fleetSectionShown&&this.refreshFleet(),this.fleetSectionShown=e}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Km(this.sessionWarningVisibility,e===void 0?void 0:Js(L(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=L(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}markSessionsRead(e){let t=L(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=wA(e,t);await this.updateComplete,!(!this.unreadConnected||TA(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}refreshInterruptedRuns(e){this.sessions.loadInterruptedRuns(e).then(e=>{this.interruptedSessionIds=e})}updateSubagentPolling(){let e=bm({hasSelectedSession:this.state.selectedSession!==void 0,documentVisible:document.visibilityState===`visible`});if(e&&this.subagentPollTimer===void 0){this.subagentPollTimer=window.setInterval(()=>{this.refreshSubagents()},sA);return}!e&&this.subagentPollTimer!==void 0&&(window.clearInterval(this.subagentPollTimer),this.subagentPollTimer=void 0)}openSubagent(e){let t=this.quickSwitcherSessions.find(t=>t.id===e.sessionId)??this.state.sessions.find(t=>t.id===e.sessionId);t!==void 0&&this.selectNavigationItem(`sessions`,`chat`,()=>this.sessions.selectSession(t))}async refreshSubagents(){let e=this.state.selectedSession;if(e!==void 0)try{let t=L(this.state),[n,r]=await Promise.all([Mo.subsessions(e,t),Mo.backgroundTasks(e,t).catch(()=>this.state.backgroundTasks)]);if(this.state.selectedSession?.id!==e.id||L(this.state)!==t)return;let i=!MA(n.subsessions,this.state.subagents),a=!NA(n.toolRuns,this.state.subagentRuns),o=!jA(r,this.state.backgroundTasks);if(!i&&!a&&!o)return;this.setState({subagents:n.subsessions,subagentRuns:n.toolRuns,backgroundTasks:r})}catch{}}async refreshSelfUpdate(){if(!(Date.now()<this.selfUpdateCooldownUntil)){this.selfUpdateCooldownUntil=Date.now()+6e4;try{let e=await wo.status();this.setState({selfUpdate:e})}catch(e){console.warn(`Self-update status check failed`,e)}}}async applySelfUpdate(){if(!this.state.selfUpdateApplying){this.setState({selfUpdateApplying:!0});try{let e=await wo.apply();e.started||(this.setState({selfUpdateApplying:!1}),e.error!==void 0&&(this.setState({error:`Update failed: ${e.error}`}),this.scheduleTransientErrorDismissal(`Update failed: ${e.error}`)))}catch{this.setState({selfUpdateApplying:!1}),this.setState({error:`Update request failed`}),this.scheduleTransientErrorDismissal(`Update request failed`)}}}skipSelfUpdate(){let e=this.state.selfUpdate?.latest;if(e!==void 0){try{window.localStorage.setItem(`piWebSelfUpdateSkipped`,e)}catch{}this.setState({selfUpdate:void 0})}}renderSelfUpdateBanner(){let e=this.state.selfUpdate;if(e===void 0||!e.enabled||!e.available)return null;if(this.state.selfUpdateApplying)return g`
5975
+ </div>`}function eA(e){return nA(e)!==void 0}var tA=6e3;function nA(e){if(/session daemon\b.*\bunavailable: connect (enoent|econnrefused)/i.test(e)&&/sessiond\.sock/i.test(e))return`Reconnecting to the session daemon…`;if(/\boperation was aborted\b/i.test(e))return`Previous request was interrupted. Retry if the message did not finish.`;if(/remote machine request cancelled/i.test(e))return`Connection changed while the request was in flight. Retrying is usually enough.`;if(/failed to fetch|load failed|networkerror when attempting to fetch/i.test(e))return`Lost connection to PI WEB. Reconnecting…`}function rA(e,t){let n=[];for(let r of e){let e=t[r.id]?.deprecatedAgentInputs;e===void 0||e.length===0||n.push({machineId:r.id,machineName:r.name,inputs:e})}return n}function iA(e){let t=e.inputs.map(aA).join(`; `);return`${e.machineName}: ${t}. Support for deprecated agent configuration inputs will be removed in a future release.`}function aA(e){let t=e.source===`config`?`config key ${e.name}`:`environment variable ${e.name}`;return e.replacement===void 0?`${t} is deprecated and ignored; remove it, there is no replacement`:`${t} is deprecated; set ${e.replacement} instead`}function oA(e){return e.length===0?null:g`<div class="deprecation-notice" role="alert">
5976
+ ${e.map(e=>g`<p class="deprecation-notice-text">${iA(e)}</p>`)}
5977
+ </div>`}var sA=900*1e3,cA=4e3,lA=15e3;function uA(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.addEventListener==`function`&&typeof t.removeEventListener==`function`}var dA=750,fA=[1e3,3e3,8e3,15e3,3e4],pA={capture:!0},mA=`auto:on`,hA=`auto:off`,gA=`theme:`,_A=$s(`core:workspace.files`),vA=$s(`core:workspace.terminal`),yA=320,bA=2,xA=`(min-width: 1181px)`,$=class extends v{constructor(...e){super(...e),this.state=Hs(),this.sessionUnread=new Im({onChange:e=>{L(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.interruptedSessionIds=new Set,this.unreadSessionIds=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new up(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Cf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new pf,{notifications:this.notifications,onSelectedSessionIdle:()=>{this.workspaces.refreshWorkspaceGoals()},onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t),this.refreshSelfUpdate()},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(L(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.machineStatus=new xc(()=>this.state,e=>{this.setState(e)}),this.auth=new Ys(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new yp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new gp),this.projects=new Cc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new _c(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new Tc(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new pc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Up,this.realtime=new qd,this.machineRealtimeSockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Tp,this.terminalSelection=new Rp,this.appShell=new Ky(this),this.browserResume=new Yy({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new cb(this),this.panelResize=new pb(this),this.navigationSections=new sb(this,()=>this.state),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=SA(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=th()??Zm,this.activeThemeId=Xm,this.isRefreshingApp=!1,this.lastScheduledError=``,this.quickSwitcherOpen=!1,this.composerCollapsed=!1,this.mobileToolSheetOpen=!1,this.quickSwitcherLoading=!1,this.quickSwitcherSessions=[],this.pinnedSessionIds=Kk(),this.quickSwitcherWorkspaces=[],this.settingsSection=Fb(),this.fleetLoading=!1,this.fleetSectionShown=!1,this.shortcutConfig={},this.workspaceUploadDefaultFolder=xs(void 0),this.sessionWarningVisibility=Wm(),this.onPopState=()=>{if(this.modalLayerOpen()){this.closeModalLayer();return}this.currentRouteMatchesUrl()||this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.sessionUnread.refreshAll(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onBrowserOnline=()=>{this.realtime.reconnectNow(),this.sessions.reconnectSocketNow(),this.checkSocketLiveness()},this.onFocusIn=e=>{this.composerCollapsed=_m(e.composedPath())},this.onFocusOut=e=>{let t=e.relatedTarget;t!==null&&(this.composerCollapsed=_m(vm(t)))},this.onDocumentVisibilityChange=()=>{this.updateSubagentPolling(),document.visibilityState===`visible`&&this.refreshSubagents()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.isRenderedModalOpen()||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.selfUpdateCooldownUntil=0,this.onVisualViewportChange=()=>{let e=hm(window.innerHeight,window.visualViewport??void 0);this.style.setProperty(`--pi-app-keyboard-inset`,`${String(Math.round(e))}px`)},this.handleSendPrompt=(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i),this.handleStopActiveWork=()=>{this.sessions.stopActiveWork().then(e=>{this.restoreToComposer(e)})},this.handleClearServerQueue=e=>{this.restoreToComposer(e),this.sessions.clearServerQueue()},this.handleOpenSubagentRun=e=>{this.sessions.openSubagentRunOutput(e)},this.handleOpenBackgroundTask=e=>{e.hasOutput&&this.sessions.openBackgroundTaskOutput(e)},this.handleCloseActivityOutput=()=>{this.sessions.closeActivityOutput()},this.handleOpenSubagentSession=e=>{this.openSubagent(e)},this.handleRecallQueuedMessage=e=>{this.sessions.recallQueuedMessage(e).then(t=>{t&&this.restoreToComposer([e])})},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Ym(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleResendMessage=e=>{this.promptEditor?.restorePrompt(e)},this.handleSelectModel=()=>{this.openModelDialog()},this.handleToggleModelEnabled=async(e,t,n)=>{let r=await this.sessions.setModelEnabled(e,t,n),i=this.state.modelDialog;r===void 0||i===void 0||this.setState({modelDialog:{...i,catalog:r,options:this.modelDialogOptions(r.filter(e=>e.enabled))}})},this.handleSelectThinking=()=>{this.openThinkingDialog()}}currentRouteMatchesUrl(){let e=this.state,t=new URL(window.location.href),n=e=>{let n=t.searchParams.get(e);return n===null||n===``?void 0:n},r=e.selectedMachine===void 0?void 0:e.selectedMachine.id;return n(`machine`)===(r===`local`?void 0:r)&&n(`project`)===(e.selectedProject===void 0?void 0:e.selectedProject.id)&&n(`workspace`)===(e.selectedWorkspace===void 0?void 0:e.selectedWorkspace.id)&&n(`session`)===(e.selectedSession===void 0?void 0:e.selectedSession.id)}closeModalLayer(){if(this.mobileToolSheetOpen){this.mobileToolSheetOpen=!1;return}if(this.quickSwitcherOpen){this.quickSwitcherOpen=!1;return}let e=this.state;if(e.actionPaletteOpen){this.setState({actionPaletteOpen:!1});return}if(e.projectDialogOpen){this.setState({projectDialogOpen:!1});return}if(e.machineDialogOpen){this.setState({machineDialogOpen:!1});return}if(e.commandDialog!==void 0){this.sessions.cancelCommand();return}if(e.modelDialog!==void 0){this.setState({modelDialog:void 0});return}if(e.thinkingDialog!==void 0){this.setState({thinkingDialog:void 0});return}if(e.themeDialog!==void 0){this.setState({themeDialog:void 0});return}if(this.sessionCleanupDialog!==void 0){this.sessionCleanupDialog=void 0;return}}listenForFormFocus(e){let t=this.renderRoot;if(uA(t)){if(e===`add`){t.addEventListener(`focusin`,this.onFocusIn),t.addEventListener(`focusout`,this.onFocusOut);return}t.removeEventListener(`focusin`,this.onFocusIn),t.removeEventListener(`focusout`,this.onFocusOut)}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=EA(this.state),this.syncSelectedSessionReadState(),this.syncFleetOnSettingsSection(),this.syncDocumentTitle()}syncDocumentTitle(){let e=this.state,t=Ok({mainView:e.mainView,selectedMachine:e.selectedMachine,selectedProject:e.selectedProject,selectedWorkspace:e.selectedWorkspace,selectedSession:e.selectedSession});document.title!==t&&(document.title=t)}syncFleetOnSettingsSection(){let e=this.settingsSection===`machines`;e&&!this.fleetSectionShown&&this.refreshFleet(),this.fleetSectionShown=e}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Km(this.sessionWarningVisibility,e===void 0?void 0:Js(L(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=L(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}markSessionsRead(e){let t=L(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=TA(e,t);await this.updateComplete,!(!this.unreadConnected||EA(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}refreshInterruptedRuns(e){this.sessions.loadInterruptedRuns(e).then(e=>{this.interruptedSessionIds=e})}updateSubagentPolling(){let e=bm({hasSelectedSession:this.state.selectedSession!==void 0,documentVisible:document.visibilityState===`visible`});if(e&&this.subagentPollTimer===void 0){this.subagentPollTimer=window.setInterval(()=>{this.refreshSubagents()},cA);return}!e&&this.subagentPollTimer!==void 0&&(window.clearInterval(this.subagentPollTimer),this.subagentPollTimer=void 0)}openSubagent(e){let t=this.quickSwitcherSessions.find(t=>t.id===e.sessionId)??this.state.sessions.find(t=>t.id===e.sessionId);t!==void 0&&this.selectNavigationItem(`sessions`,`chat`,()=>this.sessions.selectSession(t))}async refreshSubagents(){let e=this.state.selectedSession;if(e!==void 0)try{let t=L(this.state),[n,r]=await Promise.all([Mo.subsessions(e,t),Mo.backgroundTasks(e,t).catch(()=>this.state.backgroundTasks)]);if(this.state.selectedSession?.id!==e.id||L(this.state)!==t)return;let i=!NA(n.subsessions,this.state.subagents),a=!PA(n.toolRuns,this.state.subagentRuns),o=!MA(r,this.state.backgroundTasks);if(!i&&!a&&!o)return;this.setState({subagents:n.subsessions,subagentRuns:n.toolRuns,backgroundTasks:r})}catch{}}async refreshSelfUpdate(){if(!(Date.now()<this.selfUpdateCooldownUntil)){this.selfUpdateCooldownUntil=Date.now()+6e4;try{let e=await wo.status();this.setState({selfUpdate:e})}catch(e){console.warn(`Self-update status check failed`,e)}}}async applySelfUpdate(){if(!this.state.selfUpdateApplying){this.setState({selfUpdateApplying:!0});try{let e=await wo.apply();e.started||(this.setState({selfUpdateApplying:!1}),e.error!==void 0&&(this.setState({error:`Update failed: ${e.error}`}),this.scheduleTransientErrorDismissal(`Update failed: ${e.error}`)))}catch{this.setState({selfUpdateApplying:!1}),this.setState({error:`Update request failed`}),this.scheduleTransientErrorDismissal(`Update request failed`)}}}skipSelfUpdate(){let e=this.state.selfUpdate?.latest;if(e!==void 0){try{window.localStorage.setItem(`piWebSelfUpdateSkipped`,e)}catch{}this.setState({selfUpdate:void 0})}}renderSelfUpdateBanner(){let e=this.state.selfUpdate;if(e===void 0||!e.enabled||!e.available)return null;if(this.state.selfUpdateApplying)return g`
5956
5978
  <div class="self-update-banner applying" role="status" aria-live="polite">
5957
5979
  <span class="state-dots"><span class="state-dot"></span><span class="state-dot"></span><span class="state-dot"></span></span>
5958
5980
  <span>正在更新 pi-web(${e.current} → ${e.latest??`new`})… 重启后页面将自动重连。</span>
@@ -5961,7 +5983,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
5961
5983
  <span>pi-web 有新版本:${e.current} → ${e.latest??`new`}</span>
5962
5984
  <button type="button" @click=${()=>{this.applySelfUpdate()}}>Update now</button>
5963
5985
  <button type="button" class="skip" @click=${()=>{this.skipSelfUpdate()}}>Skip</button>
5964
- </div>`}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions);PA(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=wA(e,t);return TA(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isRenderedModalOpen()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isRenderedModalOpen(){return zh(this.ownerDocument)}connectedCallback(){super.connectedCallback(),Ct(()=>{this.clearTransientError()}),this.unreadConnected=!0,window.visualViewport?.addEventListener(`resize`,this.onVisualViewportChange),window.visualViewport?.addEventListener(`scroll`,this.onVisualViewportChange),this.onVisualViewportChange(),window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,fA),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.syncSessionUnreadMachines(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},oA),document.addEventListener(`visibilitychange`,this.onDocumentVisibilityChange),this.listenForFormFocus(`add`),this.livenessTimer=window.setInterval(()=>{this.checkSocketLiveness()},cA),window.addEventListener(`online`,this.onBrowserOnline),this.updateSubagentPolling(),this.loadClientConfig(),this.refreshSelfUpdate(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}clearTransientError(){this.state.error===``||!$k(this.state.error)||(this.transientErrorTimer!==void 0&&(window.clearTimeout(this.transientErrorTimer),this.transientErrorTimer=void 0),this.setState({error:``}))}scheduleTransientErrorDismissal(e){this.transientErrorTimer!==void 0&&(window.clearTimeout(this.transientErrorTimer),this.transientErrorTimer=void 0),$k(e)&&(this.transientErrorTimer=window.setTimeout(()=>{this.transientErrorTimer=void 0,this.state.error===e&&this.setState({error:``})},eA))}disconnectedCallback(){Ct(void 0),this.transientErrorTimer!==void 0&&window.clearTimeout(this.transientErrorTimer),window.visualViewport?.removeEventListener(`resize`,this.onVisualViewportChange),window.visualViewport?.removeEventListener(`scroll`,this.onVisualViewportChange),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,fA),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.subagentPollTimer!==void 0&&window.clearInterval(this.subagentPollTimer),this.subagentPollTimer=void 0,this.livenessTimer!==void 0&&window.clearInterval(this.livenessTimer),this.livenessTimer=void 0,window.removeEventListener(`online`,this.onBrowserOnline),document.removeEventListener(`visibilitychange`,this.onDocumentVisibilityChange),this.listenForFormFocus(`remove`),this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!AA(this.state,e))return;let t=this.state;this.state={...this.state,...e},TA(t)!==TA(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),EA(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),DA(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedSession?.id!==this.state.selectedSession?.id&&this.updateSubagentPolling(),this.composerCollapsed&&this.state.pendingAsk===void 0&&this.state.pendingDialogs.length===0&&(this.composerCollapsed=!1)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=kb();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()}checkSocketLiveness(){document.visibilityState===`visible`&&(this.realtime.checkLiveness(),this.sessions.checkSocketLiveness())}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.realtime.checkLiveness(),this.sessions.checkSocketLiveness(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.sessionUnread.refreshAll(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineStatusSnapshots(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology()])}schedulePiWebStatusRefresh(e=uA){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshMachineStatusSnapshots(){await Promise.all(this.refreshableMachineIds().map(async e=>{try{await this.machineStatus.refresh(e)}catch(t){console.warn(`Failed to refresh machine status for ${e}`,t)}}))}refreshableMachineIds(){return this.state.machines.length===0?[L(this.state)]:this.state.machines.filter(e=>kA(e,this.state.machineStatuses[e.id])).map(e=>e.id)}async loadClientConfig(){try{this.applyClientConfig((await xo.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=xs(e),this.speechToTextConfig=e.speechToText}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineStatusSnapshots(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology()]),this.schedulePiWebStatusRefresh()}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.terminal`&&e!==void 0?await this.refreshActiveTerminals(e):await this.invalidateWorkspacePanels(t)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(kb(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=L(this.state),a=e.projectId===void 0||e.projectId===``?RA():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{if(await this.restoreRouteMachine(e,!1),await this.loadPluginsForSelectedMachine(),!this.isCurrentRouteRestore(o))return;let n=Ab(e,e=>this.plugins.resolveWorkspacePanelRouteId(e,L(this.state)));if(this.setState({workspaceTool:n.tool??this.state.workspaceTool,mainView:this.resolveRestoredMainView(r)??n.view??this.defaultRouteView(n),selectedFilePath:a.selectedFilePath,selectedTerminalId:a.selectedTerminalId}),n.projectId===void 0||n.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(n)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(n.tool,a.selectedFilePath),t&&this.updateUrl();return}let i=this.state.projects.find(e=>e.id===n.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:n.workspaceId,sessionId:n.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(n.tool,a.selectedFilePath),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),L(this.state)!==i&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?RA():{selectedFilePath:tc(gA,`file`),selectedTerminalId:tc(_A,`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){Mb(e,{replace:!0}),nc(gA,`file`,void 0,{replace:!0}),nc(_A,`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=BA(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>=dA.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(),t!==void 0&&await this.files.restoreFile(t)):e!==void 0&&e!==`core:workspace.terminal`&&await this.invalidateWorkspacePanels(e)}resolveRestoredMainView(e){return e===void 0||e===`chat`||e===`navigation`?e:jb(e,e=>this.plugins.resolveWorkspacePanelRouteId(e,L(this.state)))}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await UA(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return!this.isRenderedModalOpen()&&this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(e={}){return this.appShell.defaultRouteView(e)}updateUrl(e){this.rememberCurrentMachineNavigation(),Mb({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(Dp(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Dp(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Mb(Op(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){nc(gA,`file`,e.selectedFilePath,{replace:!0}),nc(_A,`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)??Ep(e.id);if(await this.restoreRouteFor(Op(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)}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=L(this.state)){let n=zA(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Hb(e,{api:{runTerminalCommand:(e,n)=>No.runTerminalCommand(e,n,t),listCommandRuns:e=>No.listCommandRuns(e,t),getCommandRun:e=>No.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((L(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`),L(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){nc(_A,`terminal`,e,t)}terminalWorkspaceKey(e){return`${L(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl()}openSettings(e=`general`){this.settingsSection=e,Ib(e)}async refreshFleet(){this.fleetLoading=!0,this.fleetError=void 0;try{this.fleetReport=await To.report()}catch(e){this.fleetError=e instanceof Error?e.message:String(e)}finally{this.fleetLoading=!1}}async runFleetOperation(e,t){this.fleetError=void 0;try{return await To.run(e,t)}catch(e){this.fleetError=e instanceof Error?e.message:String(e);return}finally{this.refreshFleet()}}closeSettings(){this.settingsSection=void 0,Ib(void 0)}navigateSettings(e){this.settingsSection=e,Ib(e)}restoreSettingsRoute(){this.settingsSection=Fb()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let n=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:n}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(n,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool))}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));e.add(L(this.state)),this.sessionUnread.retainMachines(e);for(let t of e)this.sessionUnread.projection(t)===void 0&&this.sessionUnread.refresh(t)}connectRealtime(){let e=L(this.state);this.refreshInterruptedRuns(e),this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.clearTransientError(),this.sessionUnread.refresh(e),this.sessions.hydrateSessionStatuses(e,{replaceKnown:!0}),this.sessions.refreshCurrentWorkspaceSessions(e),this.refreshInterruptedRuns(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t)},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 qd;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.sessionUnread.refresh(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=L(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>OA(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`machine.status`&&this.machineStatus.apply(e,t.status)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`machine.status`?this.machineStatus.apply(e,t.status):LA(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=L(this.state);try{let n=await No.terminals(e.projectId,e.id,t);if(L(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=IA(e),r=IA(t);n&&!r&&(this.setState({fileTreeStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&((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({piWebStatus:void 0}),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`?this.files.refreshFiles():e!==`core:workspace.terminal`&&this.invalidateWorkspacePanels(e)}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
5986
+ </div>`}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions);FA(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=TA(e,t);return EA(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isRenderedModalOpen()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isRenderedModalOpen(){return zh(this.ownerDocument)}connectedCallback(){super.connectedCallback(),Ct(()=>{this.clearTransientError()}),this.unreadConnected=!0,window.visualViewport?.addEventListener(`resize`,this.onVisualViewportChange),window.visualViewport?.addEventListener(`scroll`,this.onVisualViewportChange),this.onVisualViewportChange(),window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,pA),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.syncSessionUnreadMachines(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},sA),document.addEventListener(`visibilitychange`,this.onDocumentVisibilityChange),this.listenForFormFocus(`add`),this.livenessTimer=window.setInterval(()=>{this.checkSocketLiveness()},lA),window.addEventListener(`online`,this.onBrowserOnline),this.updateSubagentPolling(),this.loadClientConfig(),this.refreshSelfUpdate(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}clearTransientError(){this.state.error===``||!eA(this.state.error)||(this.transientErrorTimer!==void 0&&(window.clearTimeout(this.transientErrorTimer),this.transientErrorTimer=void 0),this.setState({error:``}))}scheduleTransientErrorDismissal(e){this.transientErrorTimer!==void 0&&(window.clearTimeout(this.transientErrorTimer),this.transientErrorTimer=void 0),eA(e)&&(this.transientErrorTimer=window.setTimeout(()=>{this.transientErrorTimer=void 0,this.state.error===e&&this.setState({error:``})},tA))}disconnectedCallback(){Ct(void 0),this.transientErrorTimer!==void 0&&window.clearTimeout(this.transientErrorTimer),window.visualViewport?.removeEventListener(`resize`,this.onVisualViewportChange),window.visualViewport?.removeEventListener(`scroll`,this.onVisualViewportChange),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,pA),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.subagentPollTimer!==void 0&&window.clearInterval(this.subagentPollTimer),this.subagentPollTimer=void 0,this.livenessTimer!==void 0&&window.clearInterval(this.livenessTimer),this.livenessTimer=void 0,window.removeEventListener(`online`,this.onBrowserOnline),document.removeEventListener(`visibilitychange`,this.onDocumentVisibilityChange),this.listenForFormFocus(`remove`),this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!jA(this.state,e))return;let t=this.state;this.state={...this.state,...e},EA(t)!==EA(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),DA(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),OA(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedSession?.id!==this.state.selectedSession?.id&&this.updateSubagentPolling(),this.composerCollapsed&&this.state.pendingAsk===void 0&&this.state.pendingDialogs.length===0&&(this.composerCollapsed=!1)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=kb();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()}checkSocketLiveness(){document.visibilityState===`visible`&&(this.realtime.checkLiveness(),this.sessions.checkSocketLiveness())}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.realtime.checkLiveness(),this.sessions.checkSocketLiveness(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.sessionUnread.refreshAll(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineStatusSnapshots(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology()])}schedulePiWebStatusRefresh(e=dA){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshMachineStatusSnapshots(){await Promise.all(this.refreshableMachineIds().map(async e=>{try{await this.machineStatus.refresh(e)}catch(t){console.warn(`Failed to refresh machine status for ${e}`,t)}}))}refreshableMachineIds(){return this.state.machines.length===0?[L(this.state)]:this.state.machines.filter(e=>AA(e,this.state.machineStatuses[e.id])).map(e=>e.id)}async loadClientConfig(){try{this.applyClientConfig((await xo.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=xs(e),this.speechToTextConfig=e.speechToText}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineStatusSnapshots(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology()]),this.schedulePiWebStatusRefresh()}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.terminal`&&e!==void 0?await this.refreshActiveTerminals(e):await this.invalidateWorkspacePanels(t)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(kb(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=L(this.state),a=e.projectId===void 0||e.projectId===``?zA():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{if(await this.restoreRouteMachine(e,!1),await this.loadPluginsForSelectedMachine(),!this.isCurrentRouteRestore(o))return;let n=Ab(e,e=>this.plugins.resolveWorkspacePanelRouteId(e,L(this.state)));if(this.setState({workspaceTool:n.tool??this.state.workspaceTool,mainView:this.resolveRestoredMainView(r)??n.view??this.defaultRouteView(n),selectedFilePath:a.selectedFilePath,selectedTerminalId:a.selectedTerminalId}),n.projectId===void 0||n.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(n)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(n.tool,a.selectedFilePath),t&&this.updateUrl();return}let i=this.state.projects.find(e=>e.id===n.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:n.workspaceId,sessionId:n.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(n.tool,a.selectedFilePath),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),L(this.state)!==i&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?zA():{selectedFilePath:tc(_A,`file`),selectedTerminalId:tc(vA,`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){Mb(e,{replace:!0}),nc(_A,`file`,void 0,{replace:!0}),nc(vA,`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=VA(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>=fA.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(),t!==void 0&&await this.files.restoreFile(t)):e!==void 0&&e!==`core:workspace.terminal`&&await this.invalidateWorkspacePanels(e)}resolveRestoredMainView(e){return e===void 0||e===`chat`||e===`navigation`?e:jb(e,e=>this.plugins.resolveWorkspacePanelRouteId(e,L(this.state)))}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await WA(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return!this.isRenderedModalOpen()&&this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(e={}){return this.appShell.defaultRouteView(e)}updateUrl(e){this.rememberCurrentMachineNavigation(),Mb({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(Dp(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Dp(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Mb(Op(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){nc(_A,`file`,e.selectedFilePath,{replace:!0}),nc(vA,`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)??Ep(e.id);if(await this.restoreRouteFor(Op(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)}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=L(this.state)){let n=BA(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Hb(e,{api:{runTerminalCommand:(e,n)=>No.runTerminalCommand(e,n,t),listCommandRuns:e=>No.listCommandRuns(e,t),getCommandRun:e=>No.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((L(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`),L(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){nc(vA,`terminal`,e,t)}terminalWorkspaceKey(e){return`${L(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl()}openSettings(e=`general`){this.settingsSection=e,Ib(e)}async refreshFleet(){this.fleetLoading=!0,this.fleetError=void 0;try{this.fleetReport=await To.report()}catch(e){this.fleetError=e instanceof Error?e.message:String(e)}finally{this.fleetLoading=!1}}async runFleetOperation(e,t){this.fleetError=void 0;try{return await To.run(e,t)}catch(e){this.fleetError=e instanceof Error?e.message:String(e);return}finally{this.refreshFleet()}}closeSettings(){this.settingsSection=void 0,Ib(void 0)}navigateSettings(e){this.settingsSection=e,Ib(e)}restoreSettingsRoute(){this.settingsSection=Fb()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let n=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:n}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(n,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool))}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));e.add(L(this.state)),this.sessionUnread.retainMachines(e);for(let t of e)this.sessionUnread.projection(t)===void 0&&this.sessionUnread.refresh(t)}connectRealtime(){let e=L(this.state);this.refreshInterruptedRuns(e),this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.clearTransientError(),this.sessionUnread.refresh(e),this.sessions.hydrateSessionStatuses(e,{replaceKnown:!0}),this.sessions.refreshCurrentWorkspaceSessions(e),this.refreshInterruptedRuns(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t)},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 qd;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.sessionUnread.refresh(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=L(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>kA(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`machine.status`&&this.machineStatus.apply(e,t.status)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`machine.status`?this.machineStatus.apply(e,t.status):RA(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=L(this.state);try{let n=await No.terminals(e.projectId,e.id,t);if(L(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=LA(e),r=LA(t);n&&!r&&(this.setState({fileTreeStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&((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({piWebStatus:void 0}),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`?this.files.refreshFiles():e!==`core:workspace.terminal`&&this.invalidateWorkspacePanels(e)}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
5965
5987
  <workspace-panel
5966
5988
  id="workspace-panel"
5967
5989
  .workspace=${e}
@@ -6007,7 +6029,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6007
6029
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
6008
6030
  .onReset=${()=>{this.resetResizablePanel(`workspace`)}}
6009
6031
  ></app-panel-edge-control>
6010
- `}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-yA-vA);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(bA).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()}selectedMachineRuntime(){return this.state.machineRuntimes[L(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){let t=L(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await Mo.cleanupPreview(e,t);if(L(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){L(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${VA(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Tm(t.previewRequest)!==Tm(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}let n=L(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await Mo.cleanup(e,n);if(L(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){L(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${VA(e)}`})}}renderNavigationPanel(){return g`
6032
+ `}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-bA-yA);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(xA).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()}selectedMachineRuntime(){return this.state.machineRuntimes[L(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){let t=L(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await Mo.cleanupPreview(e,t);if(L(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){L(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${HA(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Tm(t.previewRequest)!==Tm(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}let n=L(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await Mo.cleanup(e,n);if(L(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){L(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${HA(e)}`})}}renderNavigationPanel(){return g`
6011
6033
  <app-navigation-panel
6012
6034
  .machines=${this.state.machines}
6013
6035
  .selectedMachine=${this.state.selectedMachine}
@@ -6077,7 +6099,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6077
6099
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
6078
6100
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
6079
6101
  ></app-navigation-panel>
6080
- `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;if(await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),!i())return;let a=t;e===`projects`&&(this.navigationSections.advanceAfterSelection(`projects`,{workspaceCount:this.state.workspaces.length}),this.state.workspaces.length===1&&this.state.selectedWorkspace!==void 0&&(a=`sessions`)),await this.focusNavigationTarget(a)}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}canStartSession(){return this.state.selectedWorkspace!==void 0}activeSessionIds(){let e=new Set;for(let t of this.quickSwitcherSessions)Us(this.state.sessionStatuses[t.id],this.state.sessionActivities[t.id])&&e.add(t.id);return e}sessionStateKinds(){return hD(this.quickSwitcherSessions,this.state.sessionStatuses,this.state.sessionActivities)}errorSessionIds(){let e=new Set;for(let[t,n]of this.sessionStateKinds())n===`error`&&e.add(t);return e}togglePinnedSession(e){this.pinnedSessionIds=qk(this.pinnedSessionIds,e.id),Kk(this.pinnedSessionIds)}waitingSessionIds(){let e=new Set;for(let t of this.quickSwitcherSessions)Sm(this.state.sessionStatuses[t.id])&&e.add(t.id);return e}modalLayerOpen(){return this.quickSwitcherOpen||this.mobileToolSheetOpen||this.state.actionPaletteOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.sessionCleanupDialog!==void 0}pushModalLayerFrame(){window.history.pushState({},``)}openActionPalette(){this.pushModalLayerFrame(),this.setState({actionPaletteOpen:!0})}openProjectDialog(){this.pushModalLayerFrame(),this.setState({projectDialogOpen:!0})}openQuickSwitcher(){Zk(),this.quickSwitcherOpen=!0,this.pushModalLayerFrame(),this.loadQuickSwitcherData(this.quickSwitcherSessions.length>0);let e=L(this.state);e!==``&&this.refreshInterruptedRuns(e)}applyRenameToQuickSwitcher(e,t){this.quickSwitcherSessions=mD(this.quickSwitcherSessions,e,t)}async loadQuickSwitcherData(e=!1){let t=L(this.state);if(!(!e&&this.quickSwitcherMachineId===t&&(this.quickSwitcherSessions.length>0||this.quickSwitcherWorkspaces.length>0||this.quickSwitcherLoading))){this.quickSwitcherLoading=!0;try{let e=this.state.projects.length>0?this.state.projects:await ko.projects(t),n=FA((await Promise.all(e.map(async e=>{try{return await jo.workspaces(e.id,t)}catch{return[]}}))).flat()),r=await Promise.all(n.map(async e=>{try{return await Mo.sessions(e.path,t)}catch{return[]}}));this.quickSwitcherMachineId=t,this.quickSwitcherWorkspaces=n,this.quickSwitcherSessions=FA(r.flat()).sort((e,t)=>Date.parse(t.modified)-Date.parse(e.modified))}catch(e){L(this.state)===t&&this.setState({error:`Failed to load sessions: ${VA(e)}`})}finally{L(this.state)===t&&(this.quickSwitcherLoading=!1)}}}async openSessionFromQuickSwitcher(e){await this.sessions.selectSession(e),await this.focusChatComposer()}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`&&!Fk(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 UA(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await UA(),!this.isRenderedModalOpen()&&this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=L(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&L(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}async forkSessionTree(e){return this.sessions.forkFromTree(e)}async openSessionTree(e){this.state.selectedSession?.id!==e.id&&await this.sessions.selectSession(e),await this.sessions.runCommand(`/tree`)}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
6102
+ `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;if(await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),!i())return;let a=t;e===`projects`&&(this.navigationSections.advanceAfterSelection(`projects`,{workspaceCount:this.state.workspaces.length}),this.state.workspaces.length===1&&this.state.selectedWorkspace!==void 0&&(a=`sessions`)),await this.focusNavigationTarget(a)}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}canStartSession(){return this.state.selectedWorkspace!==void 0}activeSessionIds(){let e=new Set;for(let t of this.quickSwitcherSessions)Us(this.state.sessionStatuses[t.id],this.state.sessionActivities[t.id])&&e.add(t.id);return e}sessionStateKinds(){return gD(this.quickSwitcherSessions,this.state.sessionStatuses,this.state.sessionActivities)}errorSessionIds(){let e=new Set;for(let[t,n]of this.sessionStateKinds())n===`error`&&e.add(t);return e}togglePinnedSession(e){this.pinnedSessionIds=Jk(this.pinnedSessionIds,e.id),qk(this.pinnedSessionIds)}waitingSessionIds(){let e=new Set;for(let t of this.quickSwitcherSessions)Sm(this.state.sessionStatuses[t.id])&&e.add(t.id);return e}modalLayerOpen(){return this.quickSwitcherOpen||this.mobileToolSheetOpen||this.state.actionPaletteOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.sessionCleanupDialog!==void 0}pushModalLayerFrame(){window.history.pushState({},``)}openActionPalette(){this.pushModalLayerFrame(),this.setState({actionPaletteOpen:!0})}openProjectDialog(){this.pushModalLayerFrame(),this.setState({projectDialogOpen:!0})}openQuickSwitcher(){Qk(),this.quickSwitcherOpen=!0,this.pushModalLayerFrame(),this.loadQuickSwitcherData(this.quickSwitcherSessions.length>0);let e=L(this.state);e!==``&&this.refreshInterruptedRuns(e)}applyRenameToQuickSwitcher(e,t){this.quickSwitcherSessions=hD(this.quickSwitcherSessions,e,t)}async loadQuickSwitcherData(e=!1){let t=L(this.state);if(!(!e&&this.quickSwitcherMachineId===t&&(this.quickSwitcherSessions.length>0||this.quickSwitcherWorkspaces.length>0||this.quickSwitcherLoading))){this.quickSwitcherLoading=!0;try{let e=this.state.projects.length>0?this.state.projects:await ko.projects(t),n=IA((await Promise.all(e.map(async e=>{try{return await jo.workspaces(e.id,t)}catch{return[]}}))).flat()),r=await Promise.all(n.map(async e=>{try{return await Mo.sessions(e.path,t)}catch{return[]}}));this.quickSwitcherMachineId=t,this.quickSwitcherWorkspaces=n,this.quickSwitcherSessions=IA(r.flat()).sort((e,t)=>Date.parse(t.modified)-Date.parse(e.modified))}catch(e){L(this.state)===t&&this.setState({error:`Failed to load sessions: ${HA(e)}`})}finally{L(this.state)===t&&(this.quickSwitcherLoading=!1)}}}async openSessionFromQuickSwitcher(e){await this.sessions.selectSession(e),await this.focusChatComposer()}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`&&!Ik(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 WA(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await WA(),!this.isRenderedModalOpen()&&this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=L(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&L(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}async forkSessionTree(e){return this.sessions.forkFromTree(e)}async openSessionTree(e){this.state.selectedSession?.id!==e.id&&await this.sessions.selectSession(e),await this.sessions.runCommand(`/tree`)}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
6081
6103
  <session-tree-navigator
6082
6104
  .tree=${e.treeDialog}
6083
6105
  .onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
@@ -6085,13 +6107,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6085
6107
  .onAbort=${()=>this.sessions.abortTreeNavigation()}
6086
6108
  .onCancel=${()=>{this.closeSessionTreeNavigator()}}
6087
6109
  ></session-tree-navigator>
6088
- `}visibleWorkspacePanels(){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)}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:`Loading projects…`,body:`Looking for projects you have added to PI WEB.`}:e===void 0?this.state.projects.length===0?{title:`No projects yet`,body:`Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace.`}:{title:`Select a project`,body:`Choose a project from the sidebar, then select a workspace to use its tools.`}: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 use its tools.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?`Loading projects…`: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.`}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=CA(this.state),n=r=>{let i=Iy(r,e,t.id);return Ay({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),...i===void 0?{}:{backend:i},host:this.createWorkspaceHost()},n)};return n(SA())}createWorkspaceFiles(e,t){return Ly(jo,e,t,()=>{this.files.refreshFiles()})}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=CA(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i.registrationPluginId,n),o=Iy(i,e,n);return ky({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),...o===void 0?{}:{backend:o},prompt:this.createPromptEditor(),terminal:{open:t=>{this.openRuntimeTerminal(n,e,t)},runCommand:t=>a.runCommand({...t,workspace:e})},openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,selectedFileLoadError:this.state.selectedFileLoadError,fileTreeStale:this.state.fileTreeStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Ss(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)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(SA())}invalidateWorkspacePanels(e){let t=this.state.selectedWorkspace;return t===void 0?Promise.resolve():this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(t),e)}getActions(){return zb(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.workspaceSurfaceActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}workspaceSurfaceActions(){return[{id:`core:workspace.refresh-current`,title:`Refresh Current Panel`,shortcut:`mod+shift+r`,group:`Workspace`,enabled:this.state.selectedWorkspace!==void 0,run:()=>this.refreshCurrentWorkspaceSurface()}]}sessionActions(){return[{id:`app.sessions.quick-switch`,title:`Open Session`,description:`Search and open a session, or start a new one, without walking the navigation panel`,shortcut:`mod+p`,group:`Sessions`,run:()=>{this.openQuickSwitcher()}},{id:`app.sessions.new`,title:`New Session`,description:`Start a session in the selected workspace`,shortcut:`mod+shift+n`,group:`Sessions`,enabled:this.canStartSession(),...this.canStartSession()?{}:{disabledReason:`Select a workspace first`},run:()=>{this.startSessionAndOpenChat()}},{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,title:`Reset Navigation Panel Size`,description:`Restore the navigation panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`Reset Workspace Panel Size`,description:`Restore the workspace panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`Reset Panel Sizes`,description:`Restore all side panels to their default widths`,group:`View`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`Focus Machines`,description:`Move keyboard focus to the machine selector`,shortcut:`mod+g m`,group:`Navigation`,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`Focus Projects`,description:`Move keyboard focus to the projects list`,shortcut:`mod+g p`,group:`Navigation`,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`Focus Workspaces`,description:`Move keyboard focus to the workspaces list`,shortcut:`mod+g w`,group:`Navigation`,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`Focus Sessions`,description:`Move keyboard focus to the sessions list`,shortcut:`mod+g s`,group:`Navigation`,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){let e=this.gatewayPluginLoadPromise;if(e!==void 0)return e;let t=this.loadExternalPlugins().then(e=>{!e&&this.gatewayPluginLoadPromise===t&&(this.gatewayPluginLoadPromise=void 0)});return this.gatewayPluginLoadPromise=t,t}loadExternalPlugins(){return this.registerExternalPlugins(`PI WEB plugins`,()=>oy(`pi-web-plugins/manifest.json`,{shouldLoadPlugin:e=>!this.plugins.hasPlugin(e.id)}))}async loadPluginsForSelectedMachine(){await this.ensureGatewayPluginsLoaded();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.state.machineRuntimes[e.id];if(t?.ok===!0&&!qt(t,kt.pluginLifecycle)){console.warn(`PI WEB plugins from ${e.name} require a matching plugin lifecycle capability; update and restart PI WEB on that machine`);return}let n=this.machinePluginLoadPromises.get(e.id);if(n!==void 0)return n;let r=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>oy(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:t=>!this.plugins.hasPlugin(Gs(e.id,t.id))&&this.plugins.shouldLoadRemotePlugin(t.id,t.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,r),await r}async registerExternalPlugins(e,t){try{let e=await t(),n=e.failures.length===0;for(let t of e.failures)console.warn(`Failed to load PI WEB plugin ${t.entry.id} (${t.entry.module})`,t.error);for(let t of e.registrations)if(!this.plugins.hasPlugin(t.id))try{this.plugins.register(t)}catch(e){n=!1,console.warn(`Failed to register PI WEB plugin ${t.id}`,e)}return this.applyPreferredTheme(!1),this.requestUpdate(),n}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Oy({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.openActionPalette()},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()},openModelPicker:()=>this.openModelDialog(),openThinkingLevelPicker:()=>this.openThinkingDialog(),selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshWorkspacePanels:e=>this.invalidateWorkspacePanels(e),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.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:async()=>{await this.sessions.stopActiveWork()}},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!mh(e)){this.setState({error:`Workspace removal is not available`});return}if(yh(this.state,e))return;let t=e.removal,n=hh(e);if(t===void 0||n===void 0||!confirm(n))return;let r=L(this.state);try{let n=await jo.deleteWorkspace(e.projectId,e.id,t.precondition,r);if(L(this.state)!==r)return;this.recordWorkspaceDeletionRun(n,r);let i=await this.workspaceForCommandRun(n);if(L(this.state)!==r)return;i!==void 0&&this.openRuntimeTerminal(r,i,{terminalId:n.terminalId})}catch(e){L(this.state)===r&&this.setState({error:`Failed to start workspace removal: ${VA(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(L(this.state)!==t)return;let n=bh(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=L(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(gh(t.id));if(L(this.state)!==e)return;let r=_h(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))xh(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(xh);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=L(this.state)){if(L(this.state)!==t)return;let n=zA(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=bh(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),L(this.state)!==t)return;this.setState({workspaceDeletionRuns:HA(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace removal failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}async focusPromptEditorSoon(){await this.updateComplete,this.promptEditor?.focusInput()}openMachineDialog(){this.pushModalLayerFrame(),this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async renameMachine(e,t){let n=t.trim();n===``||n===e.name||await this.machines.updateMachine(e,{name:n})}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 WEB 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,t]=await Promise.all([this.sessions.listModels(),this.sessions.listModelCatalog()]),n=this.currentModelValue();this.setState({modelDialog:{title:`Select Model`,...n===void 0?{}:{selectedValue:n},options:this.modelDialogOptions(e),catalog:t}})}currentModelValue(){let e=this.state.status?.model?.provider,t=this.state.status?.model?.id;return e!==void 0&&t!==void 0?`${e}/${t}`:void 0}modelDialogOptions(e){let t=this.currentModelValue();return e.map(e=>{let n=e.provider??``,r=e.id??``,i=`${n}/${r}`;return{value:i,label:`${r}${i===t?` ✓ current`:``}`,description:n}})}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))}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?mA:pA;this.pushModalLayerFrame(),this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${hA}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${hA}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}selectTheme(e){let t=this.plugins.getThemes().find(t=>t.id===e);t!==void 0&&(this.themePreference={themeId:t.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}setFollowSystemTheme(e){this.themePreference={themeId:this.themePreference.themeId,auto:e},this.applyPreferredTheme(!0)}pickTheme(e){if(this.setState({themeDialog:void 0}),e===pA||e===mA){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===pA},this.applyPreferredTheme(!0);return}if(!e.startsWith(hA))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,rh(t),e&&nh(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return ih({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return oh(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.pushModalLayerFrame(),this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=WA(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)}async runGoalCommand(e){this.state.selectedSession!==void 0&&await this.sendPrompt(e)}async sendPrompt(e,t,n,r,i){return!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)?!0:await this.sessions.send(e,t,n,r,i)}restoreToComposer(e){let t=e.map(e=>e.text).filter(e=>e.trim()!==``);t.length!==0&&(this.promptEditor?.replaceText(t.join(`
6110
+ `}visibleWorkspacePanels(){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)}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:`Loading projects…`,body:`Looking for projects you have added to PI WEB.`}:e===void 0?this.state.projects.length===0?{title:`No projects yet`,body:`Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace.`}:{title:`Select a project`,body:`Choose a project from the sidebar, then select a workspace to use its tools.`}: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 use its tools.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?`Loading projects…`: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.`}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=wA(this.state),n=r=>{let i=Iy(r,e,t.id);return Ay({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),...i===void 0?{}:{backend:i},host:this.createWorkspaceHost()},n)};return n(CA())}createWorkspaceFiles(e,t){return Ly(jo,e,t,()=>{this.files.refreshFiles()})}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=wA(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i.registrationPluginId,n),o=Iy(i,e,n);return ky({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),...o===void 0?{}:{backend:o},prompt:this.createPromptEditor(),terminal:{open:t=>{this.openRuntimeTerminal(n,e,t)},runCommand:t=>a.runCommand({...t,workspace:e})},openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,selectedFileLoadError:this.state.selectedFileLoadError,fileTreeStale:this.state.fileTreeStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Ss(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)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(CA())}invalidateWorkspacePanels(e){let t=this.state.selectedWorkspace;return t===void 0?Promise.resolve():this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(t),e)}getActions(){return zb(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.workspaceSurfaceActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}workspaceSurfaceActions(){return[{id:`core:workspace.refresh-current`,title:`Refresh Current Panel`,shortcut:`mod+shift+r`,group:`Workspace`,enabled:this.state.selectedWorkspace!==void 0,run:()=>this.refreshCurrentWorkspaceSurface()}]}sessionActions(){return[{id:`app.sessions.quick-switch`,title:`Open Session`,description:`Search and open a session, or start a new one, without walking the navigation panel`,shortcut:`mod+p`,group:`Sessions`,run:()=>{this.openQuickSwitcher()}},{id:`app.sessions.new`,title:`New Session`,description:`Start a session in the selected workspace`,shortcut:`mod+shift+n`,group:`Sessions`,enabled:this.canStartSession(),...this.canStartSession()?{}:{disabledReason:`Select a workspace first`},run:()=>{this.startSessionAndOpenChat()}},{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,title:`Reset Navigation Panel Size`,description:`Restore the navigation panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`Reset Workspace Panel Size`,description:`Restore the workspace panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`Reset Panel Sizes`,description:`Restore all side panels to their default widths`,group:`View`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`Focus Machines`,description:`Move keyboard focus to the machine selector`,shortcut:`mod+g m`,group:`Navigation`,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`Focus Projects`,description:`Move keyboard focus to the projects list`,shortcut:`mod+g p`,group:`Navigation`,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`Focus Workspaces`,description:`Move keyboard focus to the workspaces list`,shortcut:`mod+g w`,group:`Navigation`,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`Focus Sessions`,description:`Move keyboard focus to the sessions list`,shortcut:`mod+g s`,group:`Navigation`,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){let e=this.gatewayPluginLoadPromise;if(e!==void 0)return e;let t=this.loadExternalPlugins().then(e=>{!e&&this.gatewayPluginLoadPromise===t&&(this.gatewayPluginLoadPromise=void 0)});return this.gatewayPluginLoadPromise=t,t}loadExternalPlugins(){return this.registerExternalPlugins(`PI WEB plugins`,()=>oy(`pi-web-plugins/manifest.json`,{shouldLoadPlugin:e=>!this.plugins.hasPlugin(e.id)}))}async loadPluginsForSelectedMachine(){await this.ensureGatewayPluginsLoaded();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.state.machineRuntimes[e.id];if(t?.ok===!0&&!qt(t,kt.pluginLifecycle)){console.warn(`PI WEB plugins from ${e.name} require a matching plugin lifecycle capability; update and restart PI WEB on that machine`);return}let n=this.machinePluginLoadPromises.get(e.id);if(n!==void 0)return n;let r=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>oy(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:t=>!this.plugins.hasPlugin(Gs(e.id,t.id))&&this.plugins.shouldLoadRemotePlugin(t.id,t.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,r),await r}async registerExternalPlugins(e,t){try{let e=await t(),n=e.failures.length===0;for(let t of e.failures)console.warn(`Failed to load PI WEB plugin ${t.entry.id} (${t.entry.module})`,t.error);for(let t of e.registrations)if(!this.plugins.hasPlugin(t.id))try{this.plugins.register(t)}catch(e){n=!1,console.warn(`Failed to register PI WEB plugin ${t.id}`,e)}return this.applyPreferredTheme(!1),this.requestUpdate(),n}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Oy({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.openActionPalette()},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()},openModelPicker:()=>this.openModelDialog(),openThinkingLevelPicker:()=>this.openThinkingDialog(),selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshWorkspacePanels:e=>this.invalidateWorkspacePanels(e),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.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:async()=>{await this.sessions.stopActiveWork()}},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!mh(e)){this.setState({error:`Workspace removal is not available`});return}if(yh(this.state,e))return;let t=e.removal,n=hh(e);if(t===void 0||n===void 0||!confirm(n))return;let r=L(this.state);try{let n=await jo.deleteWorkspace(e.projectId,e.id,t.precondition,r);if(L(this.state)!==r)return;this.recordWorkspaceDeletionRun(n,r);let i=await this.workspaceForCommandRun(n);if(L(this.state)!==r)return;i!==void 0&&this.openRuntimeTerminal(r,i,{terminalId:n.terminalId})}catch(e){L(this.state)===r&&this.setState({error:`Failed to start workspace removal: ${HA(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(L(this.state)!==t)return;let n=bh(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=L(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(gh(t.id));if(L(this.state)!==e)return;let r=_h(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))xh(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(xh);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=L(this.state)){if(L(this.state)!==t)return;let n=BA(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=bh(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),L(this.state)!==t)return;this.setState({workspaceDeletionRuns:UA(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace removal failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}async focusPromptEditorSoon(){await this.updateComplete,this.promptEditor?.focusInput()}openMachineDialog(){this.pushModalLayerFrame(),this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async renameMachine(e,t){let n=t.trim();n===``||n===e.name||await this.machines.updateMachine(e,{name:n})}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 WEB 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,t]=await Promise.all([this.sessions.listModels(),this.sessions.listModelCatalog()]),n=this.currentModelValue();this.setState({modelDialog:{title:`Select Model`,...n===void 0?{}:{selectedValue:n},options:this.modelDialogOptions(e),catalog:t}})}currentModelValue(){let e=this.state.status?.model?.provider,t=this.state.status?.model?.id;return e!==void 0&&t!==void 0?`${e}/${t}`:void 0}modelDialogOptions(e){let t=this.currentModelValue();return e.map(e=>{let n=e.provider??``,r=e.id??``,i=`${n}/${r}`;return{value:i,label:`${r}${i===t?` ✓ current`:``}`,description:n}})}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))}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?hA:mA;this.pushModalLayerFrame(),this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${gA}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${gA}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}selectTheme(e){let t=this.plugins.getThemes().find(t=>t.id===e);t!==void 0&&(this.themePreference={themeId:t.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}setFollowSystemTheme(e){this.themePreference={themeId:this.themePreference.themeId,auto:e},this.applyPreferredTheme(!0)}pickTheme(e){if(this.setState({themeDialog:void 0}),e===mA||e===hA){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===mA},this.applyPreferredTheme(!0);return}if(!e.startsWith(gA))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,rh(t),e&&nh(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return ih({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return oh(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.pushModalLayerFrame(),this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=GA(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)}async runGoalCommand(e){this.state.selectedSession!==void 0&&await this.sendPrompt(e)}async sendPrompt(e,t,n,r,i){return!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)?!0:await this.sessions.send(e,t,n,r,i)}restoreToComposer(e){let t=e.map(e=>e.text).filter(e=>e.trim()!==``);t.length!==0&&(this.promptEditor?.replaceText(t.join(`
6089
6111
 
6090
6112
  `)),this.promptEditor?.focusInput())}renderChatView(e,t){return g`
6091
6113
  <chat-view .goals=${this.state.workspaceGoals} .onRunGoalCommand=${(e,t)=>this.runGoalCommand(t)} .sessionId=${t.id} .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} .activity=${e.activity} .pendingAsk=${e.pendingAsk} .pendingDialogs=${e.pendingDialogs} .closedDialogs=${e.closedDialogs} .onAnswerDialog=${this.handleAnswerDialog} .onCancelDialog=${this.handleCancelDialog} .onDismissClosedDialog=${this.handleDismissClosedDialog} .onResendMessage=${this.handleResendMessage} .askDraftSessionId=${Js(L(e),t.id)} .onSubmitAsk=${this.handleSubmitAsk} .notificationInbox=${qf(e.selectedNotificationInbox)} .subagents=${e.subagents} .subagentRuns=${e.subagentRuns} .backgroundTasks=${e.backgroundTasks} .activityOutput=${e.activityOutput} .onCloseActivityOutput=${this.handleCloseActivityOutput} .onOpenSubagent=${this.handleOpenSubagentSession} .onOpenSubagentRun=${this.handleOpenSubagentRun} .onOpenBackgroundTask=${this.handleOpenBackgroundTask} .onClearServerQueue=${this.handleClearServerQueue} .onRecallQueuedMessage=${this.handleRecallQueuedMessage} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
6092
6114
  `}renderStatusBar(e){let t=this.sessionWarningVisibility.warningCount;return g`
6093
6115
  <status-bar .status=${e.status} .warningCount=${t} .warningsExpanded=${t>0&&!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings}></status-bar>
6094
- `}renderErrorBanner(e){return e!==this.lastScheduledError&&(this.lastScheduledError=e,this.scheduleTransientErrorDismissal(e)),Qk(e,()=>{this.setState({error:``})})}renderContextBar(){return this.appShell.isMobileNavigationLayout?g`
6116
+ `}renderErrorBanner(e){return e!==this.lastScheduledError&&(this.lastScheduledError=e,this.scheduleTransientErrorDismissal(e)),$k(e,()=>{this.setState({error:``})})}renderContextBar(){return this.appShell.isMobileNavigationLayout?g`
6095
6117
  <app-context-bar
6096
6118
  .machines=${this.state.machines}
6097
6119
  .machine=${this.state.selectedMachine}
@@ -6099,7 +6121,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6099
6121
  .workspace=${this.state.selectedWorkspace}
6100
6122
  .session=${this.state.selectedSession}
6101
6123
  ?emphasizeSession=${this.state.mainView===`chat`}
6102
- ?isWorking=${this.state.mainView===`chat`&&this.state.selectedSession!==void 0&&IA(this.state)}
6124
+ ?isWorking=${this.state.mainView===`chat`&&this.state.selectedSession!==void 0&&LA(this.state)}
6103
6125
  .refreshControl=${this.appShell.shouldShowAppRefreshInContextBar()?this.renderAppRefresh():void 0}
6104
6126
  .onOpenSection=${e=>{this.openNavigationSection(e)}}
6105
6127
  .onQuickSwitch=${()=>{this.openQuickSwitcher()}}
@@ -6123,7 +6145,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6123
6145
 
6124
6146
  ${this.renderErrorBanner(e.error)}
6125
6147
  ${this.renderSelfUpdateBanner()}
6126
- ${aA(nA(e.machines,e.machineRuntimes))}
6148
+ ${oA(rA(e.machines,e.machineRuntimes))}
6127
6149
  <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
6128
6150
  ${e.selectedSession?g`
6129
6151
  ${this.renderChatView(e,e.selectedSession)}
@@ -6169,4 +6191,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
6169
6191
  ${e.themeDialog===void 0?null:g`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${e=>{this.pickTheme(e)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`}
6170
6192
  ${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)}} .machines=${e.machines} .machineStatuses=${e.machineStatuses} .onAddMachine=${()=>{this.openMachineDialog()}} .onRenameMachine=${async(e,t)=>{await this.renameMachine(e,t)}} .onRemoveMachine=${e=>{this.removeMachine(e)}} .fleetReport=${this.fleetReport} ?fleetLoading=${this.fleetLoading} .fleetError=${this.fleetError} .onRefreshFleet=${()=>this.refreshFleet()} .onRunFleet=${(e,t)=>this.runFleetOperation(e,t)} .themes=${this.plugins.getThemes()} .selectedThemeId=${this.resolveCurrentThemePreference().selectedTheme?.id} .activeThemeId=${this.activeThemeId} ?followSystemTheme=${this.themePreference.auto} .onSelectTheme=${e=>{this.selectTheme(e)}} .onToggleFollowSystem=${e=>{this.setFollowSystemTheme(e)}}></settings-dialog>`}
6171
6193
  </div>
6172
- `}static{this.styles=ng}};H([x()],$.prototype,`state`,void 0),H([S(`chat-view`)],$.prototype,`chatView`,void 0),H([S(`prompt-editor`)],$.prototype,`promptEditor`,void 0),H([S(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),H([S(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),H([S(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),H([x()],$.prototype,`interruptedSessionIds`,void 0),H([x()],$.prototype,`unreadSessionIds`,void 0),H([x()],$.prototype,`activeThemeId`,void 0),H([x()],$.prototype,`isRefreshingApp`,void 0),H([x()],$.prototype,`quickSwitcherOpen`,void 0),H([x()],$.prototype,`composerCollapsed`,void 0),H([x()],$.prototype,`mobileToolSheetOpen`,void 0),H([x()],$.prototype,`quickSwitcherLoading`,void 0),H([x()],$.prototype,`quickSwitcherSessions`,void 0),H([x()],$.prototype,`pinnedSessionIds`,void 0),H([x()],$.prototype,`quickSwitcherWorkspaces`,void 0),H([x()],$.prototype,`sessionCleanupDialog`,void 0),H([x()],$.prototype,`settingsSection`,void 0),H([x()],$.prototype,`fleetReport`,void 0),H([x()],$.prototype,`fleetLoading`,void 0),H([x()],$.prototype,`fleetError`,void 0),H([x()],$.prototype,`shortcutConfig`,void 0),H([x()],$.prototype,`workspaceUploadDefaultFolder`,void 0),H([x()],$.prototype,`speechToTextConfig`,void 0),$=H([y(`pi-web-app`)],$);function xA(){let e=new wy;return e.register({id:`core`,plugin:Qv}),e.register({id:`themes`,plugin:ay}),e}function SA(){return{registrationPluginId:`core`,sourcePluginId:`core`}}function CA(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 wA(e,t){return JSON.stringify([e,t.id,t.cwd])}function TA(e){let t=e.selectedSession;return t===void 0?void 0:wA(L(e),t)}function EA(e,t){return e.machines!==t.machines}function DA(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function OA(e,t){return kA(e,t)}function kA(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function AA(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function jA(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.id===e.id&&r.status===e.status&&r.exitCode===e.exitCode&&r.durationMs===e.durationMs})}function MA(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.sessionId===e.sessionId&&r.status===e.status})}function NA(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.runId===e.runId&&r.status===e.status&&r.elapsedMs===e.elapsedMs&&r.lastActivity===e.lastActivity})}function PA(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function FA(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function IA(e){return Us(e.status,e.activity)}function LA(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function RA(){return{}}function zA(e,t){return JSON.stringify([e,t])}function BA(e){return dA[Math.min(e,dA.length-1)]??3e4}function VA(e){return e instanceof Error?e.message:String(e)}function HA(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function UA(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function WA(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{h as _,dg as a,hs as c,x as d,b as f,g,Xe as h,pg as i,No as l,v as m,H as n,Bp as o,y as p,fg as r,zp as s,Ex as t,S as u};
6194
+ `}static{this.styles=ng}};H([x()],$.prototype,`state`,void 0),H([S(`chat-view`)],$.prototype,`chatView`,void 0),H([S(`prompt-editor`)],$.prototype,`promptEditor`,void 0),H([S(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),H([S(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),H([S(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),H([x()],$.prototype,`interruptedSessionIds`,void 0),H([x()],$.prototype,`unreadSessionIds`,void 0),H([x()],$.prototype,`activeThemeId`,void 0),H([x()],$.prototype,`isRefreshingApp`,void 0),H([x()],$.prototype,`quickSwitcherOpen`,void 0),H([x()],$.prototype,`composerCollapsed`,void 0),H([x()],$.prototype,`mobileToolSheetOpen`,void 0),H([x()],$.prototype,`quickSwitcherLoading`,void 0),H([x()],$.prototype,`quickSwitcherSessions`,void 0),H([x()],$.prototype,`pinnedSessionIds`,void 0),H([x()],$.prototype,`quickSwitcherWorkspaces`,void 0),H([x()],$.prototype,`sessionCleanupDialog`,void 0),H([x()],$.prototype,`settingsSection`,void 0),H([x()],$.prototype,`fleetReport`,void 0),H([x()],$.prototype,`fleetLoading`,void 0),H([x()],$.prototype,`fleetError`,void 0),H([x()],$.prototype,`shortcutConfig`,void 0),H([x()],$.prototype,`workspaceUploadDefaultFolder`,void 0),H([x()],$.prototype,`speechToTextConfig`,void 0),$=H([y(`pi-web-app`)],$);function SA(){let e=new wy;return e.register({id:`core`,plugin:Qv}),e.register({id:`themes`,plugin:ay}),e}function CA(){return{registrationPluginId:`core`,sourcePluginId:`core`}}function wA(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 TA(e,t){return JSON.stringify([e,t.id,t.cwd])}function EA(e){let t=e.selectedSession;return t===void 0?void 0:TA(L(e),t)}function DA(e,t){return e.machines!==t.machines}function OA(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function kA(e,t){return AA(e,t)}function AA(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function jA(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function MA(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.id===e.id&&r.status===e.status&&r.exitCode===e.exitCode&&r.durationMs===e.durationMs})}function NA(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.sessionId===e.sessionId&&r.status===e.status})}function PA(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.runId===e.runId&&r.status===e.status&&r.elapsedMs===e.elapsedMs&&r.lastActivity===e.lastActivity})}function FA(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function IA(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function LA(e){return Us(e.status,e.activity)}function RA(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function zA(){return{}}function BA(e,t){return JSON.stringify([e,t])}function VA(e){return fA[Math.min(e,fA.length-1)]??3e4}function HA(e){return e instanceof Error?e.message:String(e)}function UA(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function WA(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function GA(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{h as _,dg as a,hs as c,x as d,b as f,g,Xe as h,pg as i,No as l,v as m,H as n,Bp as o,y as p,fg as r,zp as s,Ex as t,S as u};