@hyperdreamer/pi-webui 1.26.0 → 1.26.1
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.
- package/dist/client/assets/{CodeViewer-BbtvtABF.js → CodeViewer-DAKOouFS.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-B7xq-ET5.js → UnifiedDiffViewer-CIfQkwSQ.js} +1 -1
- package/dist/client/assets/{index-sujNbkL3.js → index-Jx8Fnguv.js} +49 -17
- package/dist/client/assets/{mathjaxEngine-CBUWmGvi.js → mathjaxEngine-WPWR2qyM.js} +1 -1
- package/dist/client/index.html +1 -1
- package/package.json +2 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-DAKOouFS.js","./vendor-editor-core-vyMPzMNA.js","./vendor-editor-languages-DlEQaRIv.js","./vendor-editor-legacy-CYBnW6ZU.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Y as s,d as c,et as l,f as u,it as d,j as f,l as p,p as m,q as ee,rt as te,tt as ne,u as re}from"./vendor-editor-core-vyMPzMNA.js";import{a as ie,o as ae,s as oe}from"./vendor-editor-languages-DlEQaRIv.js";import{n as se,t as ce}from"./vendor-terminal-D8k4UKM2.js";var le=Object.defineProperty,ue=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),de=(e,t)=>{let n={};for(var r in e)le(n,r,{get:e[r],enumerable:!0});return t||le(n,Symbol.toStringTag,{value:`Module`}),n};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var fe=globalThis,pe=fe.ShadowRoot&&(fe.ShadyCSS===void 0||fe.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,me=Symbol(),he=new WeakMap,ge=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==me)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(pe&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=he.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&he.set(t,e))}return e}toString(){return this.cssText}},_e=e=>new ge(typeof e==`string`?e:e+``,void 0,me),h=(e,...t)=>new ge(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,me),ve=(e,t)=>{if(pe)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=fe.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},ye=pe?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return _e(t)})(e):e,{is:be,defineProperty:xe,getOwnPropertyDescriptor:Se,getOwnPropertyNames:Ce,getOwnPropertySymbols:we,getPrototypeOf:Te}=Object,Ee=globalThis,De=Ee.trustedTypes,Oe=De?De.emptyScript:``,ke=Ee.reactiveElementPolyfillSupport,Ae=(e,t)=>e,je={toAttribute(e,t){switch(t){case Boolean:e=e?Oe: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}},Me=(e,t)=>!be(e,t),Ne={attribute:!0,type:String,converter:je,reflect:!1,useDefault:!1,hasChanged:Me};Symbol.metadata??=Symbol(`metadata`),Ee.litPropertyMetadata??=new WeakMap;var Pe=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=Ne){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&&xe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=Se(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)??Ne}static _$Ei(){if(this.hasOwnProperty(Ae(`elementProperties`)))return;let e=Te(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Ae(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Ae(`properties`))){let e=this.properties,t=[...Ce(e),...we(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(ye(e))}else e!==void 0&&t.push(ye(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 ve(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?je: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?je: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??Me)(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){}};Pe.elementStyles=[],Pe.shadowRootOptions={mode:`open`},Pe[Ae(`elementProperties`)]=new Map,Pe[Ae(`finalized`)]=new Map,ke?.({ReactiveElement:Pe}),(Ee.reactiveElementVersions??=[]).push(`2.1.2`);var Fe=globalThis,Ie=e=>e,Le=Fe.trustedTypes,Re=Le?Le.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,ze=`$lit$`,Be=`lit$${Math.random().toFixed(9).slice(2)}$`,Ve=`?`+Be,He=`<${Ve}>`,Ue=document,We=()=>Ue.createComment(``),Ge=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Ke=Array.isArray,qe=e=>Ke(e)||typeof e?.[Symbol.iterator]==`function`,Je=`[
|
|
3
3
|
\f\r]`,Ye=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Xe=/-->/g,Ze=/>/g,Qe=RegExp(`>|${Je}(?:([^\\s"'>=/]+)(${Je}*=${Je}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),$e=/'/g,et=/"/g,tt=/^(?:script|style|textarea|title)$/i,nt=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=nt(1),_=nt(2),rt=Symbol.for(`lit-noChange`),v=Symbol.for(`lit-nothing`),it=new WeakMap,at=Ue.createTreeWalker(Ue,129);function ot(e,t){if(!Ke(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Re===void 0?t:Re.createHTML(t)}var st=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Ye;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===Ye?c[1]===`!--`?o=Xe:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=Qe):(tt.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=Qe):o=Ze:o===Qe?c[0]===`>`?(o=i??Ye,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?Qe:c[3]===`"`?et:$e):o===et||o===$e?o=Qe:o===Xe||o===Ze?o=Ye:(o=Qe,i=void 0);let d=o===Qe&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Ye?n+He:l>=0?(r.push(s),n.slice(0,l)+ze+n.slice(l)+Be+d):n+Be+(l===-2?t:d)}return[ot(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},ct=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]=st(t,n);if(this.el=e.createElement(l,r),at.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=at.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(ze)){let t=u[o++],n=i.getAttribute(e).split(Be),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?pt:r[1]===`?`?mt:r[1]===`@`?ht:ft}),i.removeAttribute(e)}else e.startsWith(Be)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(tt.test(i.tagName)){let e=i.textContent.split(Be),t=e.length-1;if(t>0){i.textContent=Le?Le.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],We()),at.nextNode(),c.push({type:2,index:++a});i.append(e[t],We())}}}else if(i.nodeType===8)if(i.data===Ve)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Be,e+1))!==-1;)c.push({type:7,index:a}),e+=Be.length-1}a++}}static createElement(e,t){let n=Ue.createElement(`template`);return n.innerHTML=e,n}};function lt(e,t,n=e,r){if(t===rt)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Ge(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=lt(e,i._$AS(e,t.values),i,r)),t}var ut=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??Ue).importNode(t,!0);at.currentNode=r;let i=at.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new dt(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new gt(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=at.nextNode(),a++)}return at.currentNode=Ue,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++}},dt=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=v,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=lt(this,e,t),Ge(e)?e===v||e==null||e===``?(this._$AH!==v&&this._$AR(),this._$AH=v):e!==this._$AH&&e!==rt&&this._(e):e._$litType$===void 0?e.nodeType===void 0?qe(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==v&&Ge(this._$AH)?this._$AA.nextSibling.data=e:this.T(Ue.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=ct.createElement(ot(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new ut(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=it.get(e.strings);return t===void 0&&it.set(e.strings,t=new ct(e)),t}k(t){Ke(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(We()),this.O(We()),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=Ie(e).nextSibling;Ie(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},ft=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=v,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=v}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=lt(this,e,t,0),a=!Ge(e)||e!==this._$AH&&e!==rt,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=lt(this,r[n+o],t,o),s===rt&&(s=this._$AH[o]),a||=!Ge(s)||s!==this._$AH[o],s===v?e=v:e!==v&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===v?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},pt=class extends ft{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===v?void 0:e}},mt=class extends ft{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==v)}},ht=class extends ft{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=lt(this,e,t,0)??v)===rt)return;let n=this._$AH,r=e===v&&n!==v||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==v&&(n===v||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},gt=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){lt(this,e)}},_t={M:ze,P:Be,A:Ve,C:1,L:st,R:ut,D:qe,V:lt,I:dt,H:ft,N:mt,U:ht,B:pt,F:gt},vt=Fe.litHtmlPolyfillSupport;vt?.(ct,dt),(Fe.litHtmlVersions??=[]).push(`3.3.3`);var yt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new dt(t.insertBefore(We(),e),e,void 0,n??{})}return i._$AI(e),i},bt=globalThis,y=class extends Pe{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=yt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return rt}};y._$litElement$=!0,y.finalized=!0,bt.litElementHydrateSupport?.({LitElement:y});var xt=bt.litElementPolyfillSupport;xt?.({LitElement:y}),(bt.litElementVersions??=[]).push(`4.2.2`);var St={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Ct=e=>(...t)=>({_$litDirective$:e,values:t}),wt=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},{I:Tt}=_t,Et=e=>e,Dt=()=>document.createComment(``),Ot=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new Tt(r.insertBefore(Dt(),i),r.insertBefore(Dt(),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=Et(e).nextSibling;Et(r).insertBefore(e,i),e=t}}}return n},kt=(e,t,n=e)=>(e._$AI(t,n),e),At={},jt=(e,t=At)=>e._$AH=t,Mt=e=>e._$AH,Nt=e=>{e._$AR(),e._$AA.remove()},Pt=Ct(class extends wt{constructor(){super(...arguments),this.key=v}render(e,t){return this.key=e,t}update(e,[t,n]){return t!==this.key&&(jt(e),this.key=t),n}}),b=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},Ft={attribute:!0,type:String,converter:je,reflect:!1,hasChanged:Me},It=(e=Ft,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function x(e){return(t,n)=>typeof n==`object`?It(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function S(e){return x({...e,state:!0,attribute:!1})}var Lt=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function C(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return Lt(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 Lt(n,r,{get(){return a(this)}})}}var Rt=/^\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)\/([!#$%&'*+.^_`|~0-9A-Za-z-]+)(?:\s*;\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)\s*=\s*([!#$%&'*+.^_`|~0-9A-Za-z.-]+))?\s*$/u;function zt(e){if(e===void 0)return;let t=Rt.exec(e);if(t===null)return;let n=t[1]?.toLowerCase(),r=t[2]?.toLowerCase(),i=t[3]?.toLowerCase(),a=t[4]?.toLowerCase(),o=n===void 0||r===void 0?void 0:`${n}/${r}`;if(o===`audio/webm`&&i===`codecs`&&a===`opus`)return`audio/webm;codecs=opus`;if(o===`audio/ogg`&&i===`codecs`&&a===`opus`)return`audio/ogg;codecs=opus`;if(o===`audio/mp4`&&i===`codecs`&&a===`mp4a.40.2`)return`audio/mp4;codecs=mp4a.40.2`;if(o===`audio/mp4`&&i===void 0)return`audio/mp4`}var w={sessionsDeleteArchived:`sessions.deleteArchived`,sessionsBulkMutations:`sessions.bulkMutations`,sessionsCleanup:`sessions.cleanup`,sessionsReload:`sessions.reload`,sessionsClearQueue:`sessions.clearQueue`,sessionsMessageActions:`sessions.messageActions`,sessionsSystemPrompt:`sessions.systemPrompt`,sessionsExtensionEntries:`sessions.extensionEntries`,sessionsPersistedState:`sessions.persistedState`,sessionsNotifications:`sessions.notifications`,sessionsUnread:`sessions.unread`,promptAttachments:`prompt.attachments`,workspaceFileSuggestions:`workspace.fileSuggestions`,piPackagesManage:`piPackages.manage`,selectedMachineSettings:`settings.selectedMachine`,agentProfileConfig:`settings.agentProfile`,modelTierSettings:`settings.modelTiers`,utilityModelSettings:`settings.utilityModels`,sessionsModelPolicy:`sessions.modelPolicy`,sessionsModelPolicyDefaults:`sessions.modelPolicyDefaults`,sessionsModelPolicyStarterSelection:`sessions.modelPolicyStarterSelection`,sessionsReorder:`sessions.reorder`,projectUsageStatistics:`project.usageStatistics`,sessionsModelPolicyLightweightFallback:`sessions.modelPolicyLightweightFallback`},Bt=[`economy`,`fast`,`standard`,`advanced`,`capable`,`frontier`],Vt=[`lightweight`,`context`],Ht=`session`,Ut=1e3,Wt=1e3,Gt=32*1024,Kt=8*1024,qt=1e4;function Jt(e,t=Xt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(Zt(e),n).toString()}function Yt(e,t=Xt()){let n=new URL(Jt(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 Xt(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function Zt(e){return e.startsWith(`/`)?`.${e}`:e}var Qt=class extends Error{constructor(e,t){super(e),this.status=t,this.name=`HttpRequestError`}};async function T(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(Jt(e),{...n,headers:r});if(!i.ok)throw new Qt(tn(await i.json().catch(()=>({})))??i.statusText,i.status);return t(await i.json())}async function $t(e,t){let n=new Headers(t?.headers);t?.body!==void 0&&!n.has(`content-type`)&&n.set(`content-type`,`application/json`);let r=await fetch(Jt(e),{...t,headers:n}),i=await r.json().catch(e=>{if(t?.signal?.aborted===!0||en(e))throw e});return{status:r.status,body:i}}function en(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`}function tn(e){if(nn(e))return typeof e.error==`string`?e.error:void 0}function nn(e){return typeof e==`object`&&!!e}var rn=class extends Qt{constructor(e,t,n={}){super(e,t),this.name=`ModelsConfigRequestError`,this.details=n}},an=[`MODELS_CONFIG_PARSE_FAILED`,`MODELS_CONFIG_IO_FAILED`,`MODELS_CONFIG_SAVE_INVALID`,`MODELS_CONFIG_INVALID_LIMITS`,`MODELS_CONFIG_UNREADABLE`,`MODELS_CONFIG_PERSIST_FAILED`,`MODELS_CONFIG_REFRESH_FAILED`,`MODELS_CONFIG_INTERNAL`],on=[`not-a-number`,`not-finite`,`not-an-integer`,`negative`,`unsafe-integer`,`missing-model-id`];function sn(e,t,n){let r=dn(e)?e:{};return new rn(typeof r.error==`string`&&r.error!==``?r.error:n,t,cn(r))}function cn(e){let t={},n=e.code;ln(n)&&(t.code=n),typeof e.file==`string`&&(t.file=e.file),typeof e.provider==`string`&&(t.provider=e.provider),typeof e.modelId==`string`&&(t.modelId=e.modelId);let r=e.field;(r===`tpm`||r===`rpm`)&&(t.field=r),typeof e.occurrence==`number`&&(t.occurrence=e.occurrence);let i=e.reason;return un(i)&&(t.reason=i),typeof e.persisted==`boolean`&&(t.persisted=e.persisted),t}function ln(e){return typeof e==`string`&&an.some(t=>t===e)}function un(e){return typeof e==`string`&&on.some(t=>t===e)}function dn(e){return typeof e==`object`&&!!e}function fn(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function pn(e){return!e.includes(`/`)&&!e.includes(`\\`)&&fn(e)}var mn=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),hn=/^sha256:[0-9a-f]{64}$/u,gn=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,_n=new Set([`PI_WEBUI_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function vn(e){if(!Cn(e)||Object.keys(e).some(e=>!mn.has(e)))return;let t=e.schemaVersion,n=e.revision,r=e.command,i=e.dir,a=e.sessionDirEnvKeys;if(t===1&&!(typeof n!=`string`||!hn.test(n))&&!(typeof r!=`string`||!yn(r))&&!(typeof i!=`string`||!bn(i))&&Sn(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEBUI_AGENT_SESSION_DIR`||a.some(e=>!_n.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function yn(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:bn(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):gn.test(e)}function bn(e){if(e===``||e!==e.trim()||xn(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function xn(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Sn(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Cn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var wn=Object.values(w),Tn=new Set(wn);w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsExtensionEntries,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsModelPolicyLightweightFallback,w.sessionsReorder,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsExtensionEntries,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsModelPolicyLightweightFallback,w.sessionsReorder,w.projectUsageStatistics,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsExtensionEntries,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsModelPolicyLightweightFallback,w.sessionsReorder,w.projectUsageStatistics;function En(e){return typeof e==`string`&&Tn.has(e)}function E(e,t){return e?.capabilities?.includes(t)===!0}function Dn(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(En)}var On=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function kn(e){return On.test(e)}function An(e){try{let t=Intl.getCanonicalLocales(e);return t.length===1?t[0]:void 0}catch{return}}var jn=4e3;function Mn(e){return{...e?.voice===void 0?{}:{voice:e.voice},rate:e?.rate??0}}function Nn(e){let t=e.replace(/\r\n|\r/gu,`
|
|
4
4
|
`).replace(/(?!\t|\n)\p{Cc}/gu,``),n=t.slice(0,jn);if(n.length===4e3){let e=n.charCodeAt(n.length-1),r=t.charCodeAt(jn);e>=55296&&e<=56319&&r>=56320&&r<=57343&&(n=n.slice(0,-1))}return n.trimEnd()}var Pn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function Fn(e){return Pn.test(e)}var In=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Ln(e){return In.some(t=>t===e)}function Rn(e){return e===void 0||e===``?`off`:e}function zn(e,t){let n=t.length>=2?t:In,r=n.length-1,i=Rn(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}function Bn(e){return typeof e==`object`&&!!e}function D(e){if(!Bn(e))throw Error(`Expected object response`);return e}function O(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function k(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function A(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function j(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function M(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function Vn(e){let t=jr(e,`host speech status`);Nr(t,[`available`,`reason`,`voices`],`host speech status`);let n=j(t,`available`),r=Object.hasOwn(t,`reason`)?ss(t,`reason`):void 0;if(!n&&r===void 0)throw Error(`Unavailable host speech status requires a reason`);let i=Hn(t.voices);return{available:n,...P(`reason`,r),voices:i}}function Hn(e){if(!Array.isArray(e))throw Error(`Expected host speech voices array`);let t=e.map(Un),n=new Set;for(let e of t){if(n.has(e.name))throw Error(`Duplicate host speech voice name`);n.add(e.name)}return t}function Un(e){let t=jr(e,`host speech voice`);Nr(t,[`name`,`language`,`variant`],`host speech voice`);let n=Object.hasOwn(t,`variant`)?ss(t,`variant`):void 0;return{name:ss(t,`name`),language:ss(t,`language`),...P(`variant`,n)}}function Wn(e){let t=jr(e,`host speech terminal result`);Nr(t,[`runId`,`outcome`],`host speech terminal result`);let n=qn(t,`runId`),r=t.outcome;if(r!==`ended`&&r!==`canceled`)throw Error(`Invalid host speech terminal outcome`);return{runId:n,outcome:r}}function Gn(e){let t=jr(e,`host speech stop response`);return Nr(t,[`runId`,`stopped`],`host speech stop response`),{runId:qn(t,`runId`),stopped:j(t,`stopped`)}}function Kn(e){let t=jr(e,`speech input transcription response`);Nr(t,[`text`],`speech input transcription response`);let n=ss(t,`text`);if(new TextEncoder().encode(n).byteLength>1048576)throw Error(`Speech input transcription exceeds the maximum size`);return{text:n}}function qn(e,t){let n=O(e,t);if(!Fn(n))throw Error(`Invalid host speech run ID field: ${t}`);return n}function Jn(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function Yn(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Xn(e){if(!Bn(e)||typeof e.kind!=`string`)throw Error(`Invalid memory snapshot response`);if(e.kind===`unavailable`)return{kind:`unavailable`};if(e.kind!==`data`)throw Error(`Invalid memory snapshot response`);return{kind:`data`,globalEntries:Zn(e.globalEntries),projectEntries:Zn(e.projectEntries),...typeof e.projectUnavailableMessage==`string`?{projectUnavailableMessage:e.projectUnavailableMessage}:{}}}function Zn(e){if(!Array.isArray(e))throw Error(`Invalid memory snapshot response`);return e.map(e=>{if(!Bn(e)||typeof e.id!=`string`||typeof e.content!=`string`)throw Error(`Invalid memory snapshot response`);return{id:e.id,content:e.content,...typeof e.category==`string`?{category:e.category}:{},...typeof e.created==`string`?{created:e.created}:{},...typeof e.last==`string`?{last:e.last}:{},...typeof e.failureReason==`string`?{failureReason:e.failureReason}:{}}})}function Qn(e){if(!Bn(e)||typeof e.kind!=`string`)throw Error(`Invalid learned skills snapshot response`);if(e.kind===`unavailable`)return{kind:`unavailable`};if(e.kind!==`data`)throw Error(`Invalid learned skills snapshot response`);let t=e.projectUnavailableMessage;if(t!==void 0&&typeof t!=`string`)throw Error(`Invalid learned skills snapshot response`);return{kind:`data`,globalSkills:$n(e.globalSkills),projectSkills:$n(e.projectSkills),...t===void 0?{}:{projectUnavailableMessage:t}}}function $n(e){if(!Array.isArray(e))throw Error(`Invalid learned skills snapshot response`);return e.map(er)}function er(e){let t=D(e),n=N(t,`version`),r=k(t,`created`),i=k(t,`updated`);return{id:O(t,`id`),name:O(t,`name`),description:O(t,`description`),filePath:O(t,`filePath`),...n===void 0?{}:{version:n},...r===void 0?{}:{created:r},...i===void 0?{}:{updated:i}}}function tr(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=D(e);return{messages:Jn(t.messages),start:A(t,`start`),total:A(t,`total`)}}function nr(e){let t=D(e);return M(rr)(t.machines)}function rr(e){let t=D(e),n=or(t,`kind`),r=k(t,`baseUrl`),i=sr(t,`status`),a=k(t,`statusMessage`);return{id:O(t,`id`),name:O(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:O(t,`createdAt`),updatedAt:O(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function ir(e){let t=D(e),n=sr(t,`status`),r=k(t,`error`);return{machineId:O(t,`machineId`),ok:j(t,`ok`),checkedAt:O(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:Go(t.web)},...t.sessiond===void 0?{}:{sessiond:Go(t.sessiond)},...r===void 0?{}:{error:r}}}function ar(e){let t=D(e),n=k(t,`error`);return{machineId:O(t,`machineId`),ok:j(t,`ok`),checkedAt:O(t,`checkedAt`),...P(`packageName`,k(t,`packageName`)),...P(`generatedAt`,k(t,`generatedAt`)),...t.components===void 0?{}:{components:Ho(t.components)},...t.capabilities===void 0?{}:{capabilities:Zo(t.capabilities)},...n===void 0?{}:{error:n}}}function or(e,t){let n=O(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function sr(e,t){let n=k(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 cr(e){let t=D(e),n=Ro(t.pinned,`pinned`);return{id:O(t,`id`),name:O(t,`name`),path:O(t,`path`),createdAt:O(t,`createdAt`),...n===void 0?{}:{pinned:n}}}function lr(e){let t=D(e),n=O(t,`lastUsedAt`),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical recent project timestamp`);return{id:O(t,`id`),name:O(t,`name`),path:O(t,`path`),lastUsedAt:n}}function ur(e){let t=ei(e,lr,20,`recentProjects`),n=new Set,r=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate recent project id`);if(r.has(e.path))throw Error(`Duplicate recent project path`);n.add(e.id),r.add(e.path)}return t}function dr(e){let t=D(e),n=k(t,`branch`);return{id:O(t,`id`),projectId:O(t,`projectId`),path:O(t,`path`),label:O(t,`label`),...n===void 0?{}:{branch:n},isMain:j(t,`isMain`),isGitRepo:j(t,`isGitRepo`),isGitWorktree:j(t,`isGitWorktree`),...P(`effectiveConfig`,fr(t.effectiveConfig))}}function fr(e){if(e!==void 0){if(!Bn(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...P(`uploads`,ho(e.uploads))}}}function pr(e){let t=D(e),n=k(t,`name`),r=Ro(t.persisted,`persisted`),i=k(t,`parentSessionPath`),a=k(t,`archivedAt`),o=Ro(t.pinned,`pinned`),s=t.creationSource===`session-list-plus`?t.creationSource:void 0,c=t.manualOrder===void 0?void 0:ri(t,`manualOrder`);return{id:O(t,`id`),path:O(t,`path`),cwd:O(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:O(t,`created`),modified:O(t,`modified`),messageCount:A(t,`messageCount`),firstMessage:O(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a},...o===void 0?{}:{pinned:o},...s===void 0?{}:{creationSource:s},...c===void 0?{}:{manualOrder:c}}}function mr(e){let t=D(e);return{id:O(t,`id`),cwd:O(t,`cwd`),manualOrder:ri(t,`manualOrder`)}}function hr(e){let t=D(e);return{orderedSessions:M(mr)(t.orderedSessions)}}function gr(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function _r(e){if(e!==void 0)return{id:O(D(e),`id`)}}function vr(e){let t=D(e),n=_r(t.dismiss);return{severity:gr(t.severity),message:O(t,`message`),...P(`source`,k(t,`source`)),...P(`path`,k(t,`path`)),...n===void 0?{}:{dismiss:n}}}function yr(e){return e===void 0?{}:{warnings:M(vr)(e)}}function br(e){let t=D(e);return{sessionId:O(t,`sessionId`),...P(`persisted`,Ro(t.persisted,`persisted`)),isStreaming:j(t,`isStreaming`),isCompacting:j(t,`isCompacting`),isBashRunning:j(t,`isBashRunning`),pendingMessageCount:A(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:M(gi)(t.queuedMessages),...P(`messageCount`,N(t,`messageCount`)),tokens:_i(t.tokens),cost:A(t,`cost`),...la(t.generation),...yi(t.model),...P(`modelPolicy`,t.modelPolicy===void 0?void 0:Er(t.modelPolicy)),...ua(t.contextUsage),...P(`thinkingLevel`,k(t,`thinkingLevel`)),...yr(t.warnings)}}function xr(e){let t=jr(e,`session model policy response`);if(Nr(t,[`contractVersion`,`policy`,`session`],`session model policy response`),t.contractVersion!==1)throw Error(`Invalid session model policy contract version`);let n=br(t.session);if(!Object.hasOwn(t,`policy`)){let e=n.modelPolicy?.blockedReason;if(e===void 0||e.trim()===``)throw Error(`Expected non-blank string field: blockedReason`);return{contractVersion:1,session:n}}return{contractVersion:1,policy:Sr(t.policy),session:n}}function Sr(e){let t=jr(e,`session model policy`);Nr(t,[`mode`,`exact`,`tier`],`session model policy`);let n=kr(t.mode),r=Ar(t,`session model policy`);if(n===`tiered`&&r===void 0)throw Error(`Tiered session model policy requires a tier`);return{mode:n,exact:Dr(t.exact),...P(`tier`,r)}}function Cr(e){let t=jr(e,`starter model policy preference`);Nr(t,[`mode`,`tier`],`starter model policy preference`);let n=kr(t.mode),r=Ar(t,`starter model policy preference`);if(n===`tiered`&&r===void 0)throw Error(`Tiered starter model policy preference requires a tier`);return{mode:n,...P(`tier`,r)}}function wr(e){let t=jr(e,`starter model policy preference`);return Object.hasOwn(t,`exact`)?Tr(t):Cr(t)}function Tr(e){let t=jr(e,`confirmed starter model policy preference`);Nr(t,[`mode`,`exact`,`tier`],`confirmed starter model policy preference`);let n=kr(t.mode),r=Ar(t,`confirmed starter model policy preference`);if(n===`tiered`&&r===void 0)throw Error(`Tiered confirmed starter model policy preference requires a tier`);return{mode:n,exact:Dr(t.exact),...P(`tier`,r)}}function Er(e){let t=jr(e,`session model policy status`);Nr(t,[`mode`,`tier`,`resolved`,`ladderValid`,`blockedReason`],`session model policy status`);let n=kr(t.mode),r=Ar(t,`session model policy status`);if(n===`tiered`&&r===void 0)throw Error(`Tiered session model policy status requires a tier`);return{mode:n,...P(`tier`,r),resolved:Dr(t.resolved),ladderValid:j(t,`ladderValid`),...P(`blockedReason`,k(t,`blockedReason`))}}function Dr(e){let t=jr(e,`exact selection`);return Nr(t,[`model`,`thinkingLevel`],`exact selection`),{model:Or(t.model),thinkingLevel:ss(t,`thinkingLevel`)}}function Or(e){let t=jr(e,`model reference`);return Nr(t,[`provider`,`id`],`model reference`),{provider:ss(t,`provider`),id:ss(t,`id`)}}function kr(e){if(e!==`exact`&&e!==`tiered`)throw Error(`Invalid session model policy mode`);return e}function Ar(e,t){if(!Object.hasOwn(e,`tier`))return;let n=e.tier;if(typeof n!=`string`||!Qa(n))throw Error(`Invalid ${t} tier`);return n}function jr(e,t){if(!Mr(e))throw Error(`Expected ${t} object`);return e}function Mr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Reflect.getPrototypeOf(e);return t===Object.prototype||t===null}function Nr(e,t,n){let r=Object.keys(e).find(e=>!t.includes(e));if(r!==void 0)throw Error(`Invalid ${n} field: ${r}`)}function Pr(e){let t=D(e);return{seq:A(t,`seq`),partial:t.partial??null}}function Fr(e){let t=k(D(e),`systemPrompt`);return t===void 0?{}:{systemPrompt:t}}function Ir(e){let t=D(e),n=O(t,`customType`);if(n===``)throw Error(`Expected non-empty string field: customType`);let r={customType:n,entryId:O(t,`entryId`),timestamp:O(t,`timestamp`)};return t.dataOmitted===!0?{...r,dataOmitted:!0}:(t.data!==void 0&&(r.data=t.data),r)}function Lr(e){let t=D(e);return{entries:ei(t.entries,Ir,200,`entries`),seq:ri(t,`seq`),readRevision:ri(t,`readRevision`)}}function Rr(e){let t=D(e),n=ri(t,`catalogRevision`),r=ei(t.sessions,Br,Wt,`sessions`);if(Vr(r),Hr(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:Ur(t,`catalogId`,512),catalogRevision:n,sessions:r}}function zr(e){let t=D(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=Ur(t,`sessionId`,512),r=Ur(t,`cwd`,Gt),i=Wr(t,`catalogRevision`),a=t.unread===null?null:Br(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:Ur(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Br(e){let t=D(e),n=Ur(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:Ur(t,`sessionId`,512),cwd:Ur(t,`cwd`,Gt),completionOrder:Wr(t,`completionOrder`),completedAt:n}}function Vr(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 Hr(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 Ur(e,t,n){let r=ni(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Wr(e,t){let n=ri(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function Gr(e){let t=D(e),n=qr(t.summary),r=ei(t.notifications,Jr,100,`notifications`);if(ii(r),ai(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==si(r))throw Error(`Notification snapshot severity mismatch`);let i=Yr(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:ni(t,`daemonInstanceId`),catalogRevision:ri(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Kr(e){let t=D(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=qr(t.summary),r=Yr(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=Xr(t.delta);if(i.kind===`cleared`&&!oi(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:ni(t,`daemonInstanceId`),catalogRevision:ri(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function qr(e){let t=D(e),n=ri(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=ri(t,`discardedCount`),i=Qr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:ni(t,`sessionId`),cwd:ni(t,`cwd`),inboxRevision:ri(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Jr(e){let t=D(e),n=O(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=O(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=ri(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:ni(t,`id`),message:n,truncated:j(t,`truncated`),severity:Zr(t.severity),receivedAt:r,order:i}}function Yr(e){let t=D(e);return{order:ri(t,`order`),overflowWatermark:ri(t,`overflowWatermark`)}}function Xr(e){let t=D(e);switch(t.kind){case`added`:{let e=k(t,`evictedNotificationId`);return{kind:`added`,notification:Jr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=ei(t.notificationIds,ti,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:$r(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function Zr(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function Qr(e){return e===void 0?void 0:Zr(e)}function $r(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 ei(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 ti(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function ni(e,t){let n=O(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function ri(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 ii(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 ai(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 oi(e){return e.retainedCount===0&&e.discardedCount===0}function si(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function ci(e){let t=D(e),n=t.skippedBusySessionIds===void 0?void 0:Yn(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:O(t,`generatedAt`),thresholds:pi(t.thresholds),projects:M(mi)(t.projects),totals:hi(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function li(e){let t=D(e);return{...ci(t),archivedSessionIds:Yn(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:Yn(t.deletedSessionIds,`deletedSessionIds`)}}function ui(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:Yn(t.archivedSessionIds,`archivedSessionIds`),failures:M(fi)(t.failures),generatedAt:O(t,`generatedAt`)}}function di(e){let t=D(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:Yn(t.deletedSessionIds,`deletedSessionIds`),failures:M(fi)(t.failures),generatedAt:O(t,`generatedAt`)}}function fi(e){let t=D(e);return{sessionId:O(t,`sessionId`),error:O(t,`error`)}}function pi(e){let t=D(e);return{...P(`archiveIdleDays`,N(t,`archiveIdleDays`)),...P(`deleteArchivedDays`,N(t,`deleteArchivedDays`))}}function mi(e){let t=D(e);return{cwd:O(t,`cwd`),archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function hi(e){let t=D(e);return{archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function gi(e){let t=D(e),n=O(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:O(t,`text`)}}function _i(e){let t=D(e);return{input:A(t,`input`),output:A(t,`output`),cacheRead:A(t,`cacheRead`),cacheWrite:A(t,`cacheWrite`),total:A(t,`total`)}}function vi(e){let t=D(e);return{...P(`provider`,k(t,`provider`)),...P(`id`,k(t,`id`)),...P(`name`,k(t,`name`)),...P(`contextWindow`,N(t,`contextWindow`)),...P(`reasoning`,t.reasoning)}}function yi(e){return e===void 0?{}:{model:vi(e)}}function bi(e){let t=D(e);return{models:M(vi)(t.models)}}function xi(e){let t=D(e),n=t.starterModelPolicyPreference===void 0?void 0:Cr(t.starterModelPolicyPreference),r=k(t,`starterModelPolicyPreferenceError`);if(n!==void 0&&r!==void 0)throw Error(`Session defaults cannot contain both a starter preference and preference error`);return{...t.model===void 0?{}:{model:vi(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(vi)(t.models),thinkingLevels:Yn(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function Si(e){let t=jr(e,`version-two session defaults response`);if(Nr(t,[`starterModelPolicyContractVersion`,`model`,`thinkingLevel`,`models`,`thinkingLevels`,`starterModelPolicyPreference`,`starterModelPolicyPreferenceError`],`version-two session defaults response`),t.starterModelPolicyContractVersion!==2)throw Error(`Invalid starter model policy contract version`);let n=t.starterModelPolicyPreference===void 0?void 0:wr(t.starterModelPolicyPreference),r=k(t,`starterModelPolicyPreferenceError`);if(n!==void 0&&r!==void 0)throw Error(`Session defaults cannot contain both a starter preference and preference error`);return{starterModelPolicyContractVersion:2,...t.model===void 0?{}:{model:vi(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(vi)(t.models),thinkingLevels:Yn(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function Ci(e){let t=Ei(e,`models configuration`),n=t.providers;if(n===void 0)return{...t,providers:{}};let r=Ei(n,`models configuration providers`),i={};for(let[e,t]of Object.entries(r))i[e]=wi(t);return{...t,providers:i}}function wi(e){let t=Ei(e,`models configuration provider`),n={};for(let[e,r]of Object.entries(t))n[e]=r;let r=k(t,`baseUrl`);r!==void 0&&(n.baseUrl=r);let i=k(t,`api`);i!==void 0&&(n.api=i);let a=k(t,`apiKey`);a!==void 0&&(n.apiKey=a);let o=Di(t.headers,`models configuration provider headers`);o!==void 0&&(n.headers=Oi(o,`models configuration provider headers`));let s=Di(t.compat,`models configuration provider compatibility`);s!==void 0&&(n.compat={...s});let c=Di(t.modelOverrides,`models configuration provider model overrides`);c!==void 0&&(n.modelOverrides={...c});let l=t.models;if(l!==void 0){if(!Array.isArray(l))throw Error(`Expected models configuration models array`);n.models=l.map(Ti)}return n}function Ti(e){let t=Ei(e,`models configuration model`),n={id:O(t,`id`)};for(let[e,r]of Object.entries(t))n[e]=r;n.id=O(t,`id`);let r=k(t,`name`);r!==void 0&&(n.name=r);let i=k(t,`api`);i!==void 0&&(n.api=i);let a=ws(t,`reasoning`);a!==void 0&&(n.reasoning=a);let o=Di(t.thinkingLevelMap,`models configuration thinking level map`);o!==void 0&&(n.thinkingLevelMap=ki(o));let s=t.input;if(s!==void 0){if(!Array.isArray(s)||!s.every(e=>typeof e==`string`))throw Error(`Expected models configuration model input array of strings`);n.input=[...s]}let c=N(t,`contextWindow`);c!==void 0&&(n.contextWindow=c);let l=N(t,`maxTokens`);l!==void 0&&(n.maxTokens=l);let u=Di(t.cost,`models configuration model cost`);u!==void 0&&(n.cost=Ai(u));let d=Di(t.compat,`models configuration model compatibility`);d!==void 0&&(n.compat={...d});let f=t.tpm;typeof f==`number`&&(n.tpm=f);let p=t.rpm;return typeof p==`number`&&(n.rpm=p),n}function Ei(e,t){if(!Bn(e)||Array.isArray(e))throw Error(`Expected ${t} object`);return e}function Di(e,t){if(e!==void 0)return Ei(e,t)}function Oi(e,t){let n={};for(let[r,i]of Object.entries(e)){if(typeof i!=`string`)throw Error(`Expected ${t} values to be strings`);n[r]=i}return n}function ki(e){let t={};for(let[n,r]of Object.entries(e)){if(r!==null&&typeof r!=`string`)throw Error(`Expected models configuration thinking level map values to be strings or null`);t[n]=r}return t}function Ai(e){let t={};for(let n of[`input`,`output`,`cacheRead`,`cacheWrite`]){let r=e[n];if(r!==void 0){if(typeof r!=`number`)throw Error(`Expected models configuration model cost ${n} to be a number`);t[n]=r}}return t}function ji(e){let t=D(e);if(t.success!==!0)throw Error(`Expected successful models configuration save`);let n=t.contractVersion;if(n!==void 0&&n!==1)throw Error(`Expected models configuration save contract version 1`);let r=t.revision===void 0?void 0:A(t,`revision`);return{success:!0,...n===void 0?{}:{contractVersion:1},...r===void 0?{}:{revision:r}}}function Mi(e){let t=D(e),n=new Set([`contractVersion`,`revision`,`admission`,`source`,`error`]);for(let e of Object.keys(t))if(!n.has(e))throw Error(`Unexpected models configuration limits status key: ${e}`);if(t.contractVersion!==1)throw Error(`Expected models configuration limits status contract version 1`);let r=A(t,`revision`),i=t.admission;if(i!==`ready`&&i!==`blocked`)throw Error(`Expected models configuration limits admission state`);let a=t.source;if(a!==`none`&&a!==`missing-file`&&a!==`accepted-document`&&a!==`last-known-good`)throw Error(`Expected models configuration limits source`);let o=k(t,`error`);return{contractVersion:1,revision:r,admission:i,source:a,...o===void 0?{}:{error:o}}}function Ni(e){let t=D(e);return{models:M(Pi)(t.models)}}function Pi(e){let t=D(e),n=O(t,`id`),r=k(t,`name`);return r===void 0?{id:n}:{id:n,name:r}}function Fi(e){let t=D(e),n=j(t,`ok`),r=k(t,`error`),i=t.latencyMs===void 0?void 0:A(t,`latencyMs`),a=t.status===void 0?void 0:A(t,`status`),o=k(t,`responseText`);return{ok:n,...r===void 0?{}:{error:r},...i===void 0?{}:{latencyMs:i},...a===void 0?{}:{status:a},...o===void 0?{}:{responseText:o}}}function Ii(e){let t=D(e);return{skills:M(Li)(t.skills)}}function Li(e){let t=D(e),n=D(t.sourceInfo),r=k(n,`source`),i=k(n,`scope`);return{name:O(t,`name`),description:O(t,`description`),filePath:O(t,`filePath`),baseDir:O(t,`baseDir`),disableModelInvocation:j(t,`disableModelInvocation`),sourceInfo:{...r===void 0?{}:{source:r},...i===void 0?{}:{scope:i}},...t.install===void 0?{}:{install:Ri(t.install)}}}function Ri(e){let t=D(e),n=k(t,`sourceType`),r=k(t,`skillsShUrl`),i=k(t,`skillPath`),a=k(t,`ref`),o=k(t,`versionHash`);return{package:O(t,`package`),scope:zi(t.scope),source:O(t,`source`),...n===void 0?{}:{sourceType:n},...r===void 0?{}:{skillsShUrl:r},...i===void 0?{}:{skillPath:i},...a===void 0?{}:{ref:a},...o===void 0?{}:{versionHash:o},canCheckForUpdates:j(t,`canCheckForUpdates`)}}function zi(e){if(e!==`global`&&e!==`project`)throw Error(`Expected skill install scope`);return e}function Bi(e){if(D(e).success!==!0)throw Error(`Expected successful Skills mutation`);return{success:!0}}function Vi(e){let t=D(e);return{results:M(Hi)(t.results)}}function Hi(e){let t=D(e);return{package:O(t,`package`),installs:O(t,`installs`),url:O(t,`url`)}}function Ui(e){let t=D(e);return{updates:M(Wi)(t.updates)}}function Wi(e){let t=D(e),n=k(t,`currentVersion`),r=k(t,`latestVersion`),i=k(t,`message`);return{package:O(t,`package`),scope:zi(t.scope),state:Gi(t.state),...n===void 0?{}:{currentVersion:n},...r===void 0?{}:{latestVersion:r},...i===void 0?{}:{message:i}}}function Gi(e){if(e!==`up-to-date`&&e!==`update-available`&&e!==`unsupported`&&e!==`error`)throw Error(`Expected skill update state`);return e}function Ki(e){let t=D(e);if(t.success!==!0)throw Error(`Expected successful Skills update`);let n=k(t,`output`);return{success:!0,...t.skill===void 0?{}:{skill:Li(t.skill)},...n===void 0?{}:{output:n}}}function qi(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Ji(e){let t=D(e);return{levels:M(qi)(t.levels)}}function Yi(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Xi(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 Zi(e){let t=D(e),n=t.source===void 0?void 0:Xi(t.source);return{configured:j(t,`configured`),...P(`source`,n),...P(`label`,k(t,`label`))}}function Qi(e){let t=D(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:O(t,`id`),name:O(t,`name`),authType:Yi(t.authType),status:Zi(t.status),...n===void 0?{}:{loginFlow:n}}}function $i(e){let t=D(e);return{providers:M(Qi)(t.providers)}}function ea(e){let t=D(e);return{flowId:O(t,`flowId`),providerId:O(t,`providerId`),providerName:O(t,`providerName`),status:ta(t.status),progress:M(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...P(`error`,k(t,`error`)),...P(`auth`,na(t.auth)),...P(`prompt`,ia(t.prompt)),...P(`select`,oa(t.select)),...P(`info`,sa(t.info))}}function ta(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function na(e){if(e===void 0)return;let t=D(e);return{url:O(t,`url`),...P(`instructions`,k(t,`instructions`)),...P(`deviceCode`,ra(t.deviceCode))}}function ra(e){if(e===void 0)return;let t=D(e);return{userCode:O(t,`userCode`),...P(`intervalSeconds`,N(t,`intervalSeconds`)),...P(`expiresInSeconds`,N(t,`expiresInSeconds`))}}function ia(e){if(e===void 0)return;let t=D(e),n=O(t,`kind`);if(n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0?n===`manual`?`manual_code`:`text`:aa(t.promptType);return{requestId:O(t,`requestId`),message:O(t,`message`),kind:n,promptType:r,...P(`placeholder`,k(t,`placeholder`)),...P(`allowEmpty`,ws(t,`allowEmpty`))}}function aa(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function oa(e){if(e===void 0)return;let t=D(e);return{requestId:O(t,`requestId`),message:O(t,`message`),options:M(ls)(t.options)}}function sa(e){if(e!==void 0)return M(e=>{let t=D(e);return{message:O(t,`message`),...P(`links`,t.links===void 0?void 0:M(ca)(t.links))}})(e)}function ca(e){let t=D(e);return{url:O(t,`url`),...P(`label`,k(t,`label`))}}function la(e){if(e===void 0)return{};let t=D(e);return{generation:{outputTokens:A(t,`outputTokens`),...P(`tokensPerSecond`,N(t,`tokensPerSecond`)),...P(`estimated`,ws(t,`estimated`))}}}function ua(e){if(e===void 0)return{};let t=D(e);return{contextUsage:{tokens:Ts(t,`tokens`),contextWindow:A(t,`contextWindow`),percent:Ts(t,`percent`)}}}function da(e){let t=D(e),n=O(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:O(t,`name`),source:n,...P(`description`,k(t,`description`))}}function fa(e){let t=D(e),n=O(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:O(t,`path`),kind:n}}function pa(e){let t=D(e);return{path:O(t,`path`),entries:M(ma)(t.entries),scannedAt:O(t,`scannedAt`),truncated:j(t,`truncated`)}}function ma(e){let t=D(e),n=O(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:O(t,`name`),path:O(t,`path`),type:n,...P(`size`,N(t,`size`)),...P(`modifiedAt`,k(t,`modifiedAt`))}}function ha(e){let t=D(e),n=O(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:O(t,`path`),...P(`language`,k(t,`language`)),...P(`mediaType`,ya(t.mediaType)),...P(`mimeType`,k(t,`mimeType`)),encoding:n,size:A(t,`size`),modifiedAt:O(t,`modifiedAt`),content:O(t,`content`),truncated:j(t,`truncated`),binary:j(t,`binary`)}}function ga(e){let t=D(e);return{path:O(t,`path`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`),created:j(t,`created`)}}function _a(e){let t=D(e);return{path:O(t,`path`),existed:j(t,`existed`)}}function va(e){let t=D(e);return{fromPath:O(t,`fromPath`),toPath:O(t,`toPath`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`)}}function ya(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function ba(e){let t=D(e);return{isGitRepo:j(t,`isGitRepo`),hash:O(t,`hash`),...P(`branch`,k(t,`branch`)),...P(`latestTag`,k(t,`latestTag`)),...P(`upstream`,k(t,`upstream`)),...P(`ahead`,N(t,`ahead`)),...P(`behind`,N(t,`behind`)),files:M(xa)(t.files)}}function xa(e){let t=D(e);return{path:O(t,`path`),...P(`oldPath`,k(t,`oldPath`)),index:Sa(t.index),workingTree:Sa(t.workingTree)}}function Sa(e){switch(e){case`unmodified`:case`modified`:case`added`:case`deleted`:case`renamed`:case`copied`:case`untracked`:case`ignored`:case`conflicted`:return e;default:throw Error(`Invalid git file state`)}}function Ca(e){let t=D(e);return{...P(`path`,k(t,`path`)),staged:j(t,`staged`),hash:O(t,`hash`),diff:O(t,`diff`),truncated:j(t,`truncated`)}}function wa(e){let t=D(e);return{id:O(t,`id`),cwd:O(t,`cwd`),name:O(t,`name`),createdAt:O(t,`createdAt`),exited:j(t,`exited`),...P(`exitCode`,N(t,`exitCode`)),...P(`commandRunId`,k(t,`commandRunId`))}}function Ta(e){let t=D(e);return{id:O(t,`id`),origin:O(t,`origin`),projectId:O(t,`projectId`),workspaceId:O(t,`workspaceId`),terminalId:O(t,`terminalId`),title:O(t,`title`),command:O(t,`command`),status:Ea(t.status),...P(`exitCode`,N(t,`exitCode`)),createdAt:O(t,`createdAt`),...P(`startedAt`,k(t,`startedAt`)),...P(`completedAt`,k(t,`completedAt`)),metadata:Da(t.metadata,`metadata`)}}function Ea(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function Da(e,t){let n=D(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 Oa(e){let t=D(e);return{cwd:O(t,`cwd`),hasSessionActivity:j(t,`hasSessionActivity`),hasTerminalActivity:j(t,`hasTerminalActivity`),updatedAt:O(t,`updatedAt`)}}function ka(e){let t=D(e);return{workspaces:M(Oa)(t.workspaces),generatedAt:O(t,`generatedAt`)}}function Aa(e){let t=eo(e,`utility model settings response`),n=Object.keys(t).find(e=>!Pa(e));if(n!==void 0)throw Error(`Invalid utility model settings response field: ${n}`);if(t.contractVersion===1)return ja(t);if(t.contractVersion===2)return Ma(t);if(t.contractVersion===3)return Na(t);throw Error(`Invalid utility model settings contract version`)}function ja(e){let t=k(e,`configError`);return{contractVersion:1,settings:Fa(e.settings),models:M(za)(e.models),slots:Va(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function Ma(e){let t=k(e,`configError`);return{contractVersion:2,settings:Ia(e.settings),models:M(Ba)(e.models),slots:Va(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function Na(e){let t=k(e,`configError`);return{contractVersion:3,settings:La(e.settings),models:M(Ba)(e.models),slots:Va(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function Pa(e){return e===`contractVersion`||e===`settings`||e===`models`||e===`slots`||e===`valid`||e===`configError`}function Fa(e){let t=eo(e,`settings`),n=Object.keys(t).find(e=>!Ua(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:Ja(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:Ja(t.context,`settings.context`))}}function Ia(e){let t=eo(e,`settings`),n=Object.keys(t).find(e=>!Ua(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:Ra(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:Ra(t.context,`settings.context`))}}function La(e){let t=eo(e,`settings`),n=Object.keys(t).find(e=>!Ua(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:Ra(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:t.context===`session`?Ht:Ra(t.context,`settings.context`))}}function Ra(e,t){let n=eo(e,t),r=Object.keys(n).find(e=>e!==`provider`&&e!==`id`&&e!==`thinkingLevel`);if(r!==void 0)throw Error(`Invalid utility model binding field: ${t}.${r}`);let i=ni(n,`provider`),a=ni(n,`id`),o=k(n,`thinkingLevel`);if(o===void 0)return{provider:i,id:a};if(!Ln(o))throw Error(`Invalid utility model thinking level: ${t}.thinkingLevel`);return{provider:i,id:a,thinkingLevel:o}}function za(e){let t=eo(e,`models`),n=Object.keys(t).find(e=>e!==`model`&&e!==`name`);if(n!==void 0)throw Error(`Invalid utility model option field: models.${n}`);return{model:Ja(t.model,`models.model`),...P(`name`,k(t,`name`))}}function Ba(e){let t=eo(e,`models`),n=Object.keys(t).find(e=>e!==`model`&&e!==`name`&&e!==`thinkingLevels`);if(n!==void 0)throw Error(`Invalid utility model option field: models.${n}`);let r=Yn(t.thinkingLevels,`models.thinkingLevels`).map(e=>{if(!Ln(e))throw Error(`Invalid utility model thinking levels: models.thinkingLevels`);return e});return{model:Ja(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:r}}function Va(e){let t=Wa(e,`slots`);return{lightweight:Ha(t.lightweight,`slots.lightweight`),context:Ha(t.context,`slots.context`)}}function Ha(e,t){let n=eo(e,t),r=Object.keys(n).find(e=>e!==`valid`&&e!==`reason`);if(r!==void 0)throw Error(`Invalid utility model validation field: ${t}.${r}`);return{valid:j(n,`valid`),...P(`reason`,k(n,`reason`))}}function Ua(e){return Vt.some(t=>t===e)}function Wa(e,t){let n=eo(e,t),r=Object.keys(n).find(e=>!Ua(e));if(r!==void 0)throw Error(`Invalid utility model ${t} field: unknown slot ${r}`);let i=Vt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid utility model ${t} field: missing slot ${i}`);return n}function Ga(e){let t=D(e);if(t.contractVersion!==1)throw Error(`Invalid model-tier settings contract version`);let n=t.ladder===void 0?void 0:Ka(t.ladder),r=k(t,`configError`);return{contractVersion:1,...P(`ladder`,n),models:M(Ya)(t.models),rows:Xa(t.rows),valid:j(t,`valid`),...P(`configError`,r)}}function Ka(e){let t=$a(e,`ladder`);return{economy:qa(t.economy,`ladder.economy`),fast:qa(t.fast,`ladder.fast`),standard:qa(t.standard,`ladder.standard`),advanced:qa(t.advanced,`ladder.advanced`),capable:qa(t.capable,`ladder.capable`),frontier:qa(t.frontier,`ladder.frontier`)}}function qa(e,t){let n=eo(e,t),r=Object.keys(n).find(e=>e!==`model`&&e!==`thinkingLevel`);if(r!==void 0)throw Error(`Invalid model-tier entry field: ${t}.${r}`);return{model:Ja(n.model,`${t}.model`),thinkingLevel:ni(n,`thinkingLevel`)}}function Ja(e,t){let n=eo(e,t),r=Object.keys(n).find(e=>e!==`provider`&&e!==`id`);if(r!==void 0)throw Error(`Invalid model reference field: ${t}.${r}`);return{provider:ni(n,`provider`),id:ni(n,`id`)}}function Ya(e){let t=eo(e,`models`);return{model:Ja(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:Yn(t.thinkingLevels,`models.thinkingLevels`)}}function Xa(e){let t=$a(e,`rows`);return{economy:Za(t.economy,`rows.economy`),fast:Za(t.fast,`rows.fast`),standard:Za(t.standard,`rows.standard`),advanced:Za(t.advanced,`rows.advanced`),capable:Za(t.capable,`rows.capable`),frontier:Za(t.frontier,`rows.frontier`)}}function Za(e,t){let n=eo(e,t),r=Object.keys(n).find(e=>e!==`valid`&&e!==`reason`);if(r!==void 0)throw Error(`Invalid model-tier row field: ${t}.${r}`);return{valid:j(n,`valid`),...P(`reason`,k(n,`reason`))}}function Qa(e){return Bt.some(t=>t===e)}function $a(e,t){let n=eo(e,t),r=Object.keys(n).find(e=>!Qa(e));if(r!==void 0)throw Error(`Invalid model-tier ${t} field: unknown tier ${r}`);let i=Bt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid model-tier ${t} field: missing tier ${i}`);return n}function eo(e,t){if(!Bn(e)||Array.isArray(e))throw Error(`Expected object field: ${t}`);return e}function to(e){let t=D(e);return{path:O(t,`path`),exists:j(t,`exists`),config:so(t.config),effectiveConfig:so(t.effectiveConfig),envOverrides:bo(t.envOverrides)}}function no(e){let t=jr(e,`speech input settings response`);Nr(t,[`contractVersion`,`revision`,`settings`,`credential`],`speech input settings response`);let n=t.contractVersion;if(n!==1&&n!==2)throw Error(`Invalid speech input settings contract version`);let r=O(t,`revision`);if(!kn(r))throw Error(`Invalid speech input settings revision`);return{contractVersion:n,revision:r,settings:ro(t.settings,n===2),credential:oo(t.credential)}}function ro(e,t){let n=eo(e,`speech input settings`);Nr(n,[`provider`,`language`,`polishVoiceInput`,`cloud`],`speech input settings`);let r=n.provider;if(r!==`auto`&&r!==`browser`&&r!==`cloud`)throw Error(`Invalid speech input settings provider`);let i=k(n,`language`);if(i!==void 0&&An(i)!==i)throw Error(`Invalid speech input settings language`);let a=Object.hasOwn(n,`polishVoiceInput`);if(t&&!a)throw Error(`Version-two speech input settings require polishVoiceInput`);let o=!a||j(n,`polishVoiceInput`);return{provider:r,...P(`language`,i),polishVoiceInput:o,cloud:io(n.cloud)}}function io(e){let t=eo(e,`speech input cloud settings`);Nr(t,[`baseUrl`,`model`],`speech input cloud settings`);let n=ss(t,`baseUrl`);if(!ao(n))throw Error(`Invalid speech input cloud base URL`);return{baseUrl:n,model:ss(t,`model`)}}function ao(e){try{let t=new URL(e);return t.protocol===`https:`&&t.username===``&&t.password===``&&t.search===``&&t.hash===``}catch{return!1}}function oo(e){let t=eo(e,`speech input credential status`);Nr(t,[`configured`,`source`,`resolution`],`speech input credential status`);let n=j(t,`configured`),r=t.source,i=t.resolution;if(typeof i!=`string`)throw Error(`Invalid speech input credential status`);if(!n){if(r!==void 0||i!==`missing`)throw Error(`Invalid speech input credential status`);return{configured:!1,resolution:`missing`}}if(r!==`literal`&&r!==`environment`&&r!==`command`)throw Error(`Invalid speech input credential status`);if(r===`command`){if(i!==`unchecked`)throw Error(`Invalid speech input credential status`)}else if(r===`literal`){if(i!==`resolved`)throw Error(`Invalid speech input credential status`)}else if(i!==`resolved`&&i!==`unresolved`)throw Error(`Invalid speech input credential status`);return{configured:!0,source:r,resolution:i}}function so(e){let t=D(e);return{...P(`host`,k(t,`host`)),...P(`port`,N(t,`port`)),...P(`allowedHosts`,fo(t.allowedHosts)),...P(`shortcuts`,vo(t.shortcuts)),...P(`plugins`,yo(t.plugins)),...P(`pathAccess`,po(t.pathAccess)),...P(`uploads`,ho(t.uploads)),...P(`maxUploadBytes`,N(t,`maxUploadBytes`)),...P(`agent`,co(t.agent)),...P(`tts`,lo(t.tts)),...P(`sessiond`,uo(t.sessiond)),...P(`spawnSessions`,ws(t,`spawnSessions`)),...P(`subsessions`,ws(t,`subsessions`))}}function co(e){if(e!==void 0){if(!Bn(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI agent field`);return{...P(`command`,k(e,`command`)),...P(`dir`,k(e,`dir`))}}}function lo(e){if(e===void 0)return;if(!Bn(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI tts field`);Nr(e,[`voice`,`rate`],`PI WEBUI tts`);let t=k(e,`voice`)?.trim();if(t===``)throw Error(`Invalid PI WEBUI tts voice field`);let n=N(e,`rate`);if(n!==void 0&&(!Number.isInteger(n)||n<-100||n>100))throw Error(`Invalid PI WEBUI tts rate field`);return{...P(`voice`,t),...P(`rate`,n)}}function uo(e){if(e===void 0)return;if(!Bn(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI sessiond field`);Nr(e,[`host`,`port`,`url`],`PI WEBUI sessiond`);let t=k(e,`host`)?.trim(),n=k(e,`url`)?.trim(),r=N(e,`port`);if(r!==void 0&&(!Number.isInteger(r)||r<1||r>65535))throw Error(`Invalid PI WEBUI sessiond port field`);return{...t===void 0||t===``?{}:{host:t},...r===void 0?{}:{port:r},...n===void 0||n===``?{}:{url:n}}}function fo(e){if(e!==void 0){if(e===!0)return!0;if(go(e))return e;throw Error(`Invalid PI WEBUI allowedHosts field`)}}function po(e){if(e===void 0)return;if(!Bn(e))throw Error(`Invalid PI WEBUI pathAccess field`);let t=e.allowedPaths;return{...P(`allowedPaths`,mo(t,`pathAccess.allowedPaths`))}}function mo(e,t){if(e!==void 0){if(_o(e))return e;throw Error(`Invalid PI WEBUI ${t} field`)}}function ho(e){if(e!==void 0){if(!Bn(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI uploads field`);return{...P(`defaultFolder`,k(e,`defaultFolder`))}}}function go(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function _o(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function vo(e){if(e!==void 0){if(!Bn(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEBUI shortcut field`);return[e,t]}))}}function yo(e){if(e!==void 0){if(!Bn(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!Bn(t)||Array.isArray(t))throw Error(`Invalid PI WEBUI plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEBUI plugin enabled field`);let r=t.settings;if(r!==void 0&&(!Bn(r)||Array.isArray(r)))throw Error(`Invalid PI WEBUI plugin settings field`);return[e,t]}))}}function bo(e){let t=D(e);return{host:j(t,`host`),port:j(t,`port`),allowedHosts:j(t,`allowedHosts`),spawnSessions:j(t,`spawnSessions`),subsessions:j(t,`subsessions`),agentCommand:ws(t,`agentCommand`)??!1,agentDir:ws(t,`agentDir`)??!1,...xo(t),agentSessionDir:ws(t,`agentSessionDir`)??!1,sessiondUrl:ws(t,`sessiondUrl`)??!1}}function xo(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-webui`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEBUI agentDirSource field`);return{agentDirSource:t}}function So(e){let t=D(e);return{packages:M(wo)(t.packages)}}function Co(e){let t=D(e),n=k(t,`source`),r=t.scope===void 0?void 0:To(t.scope),i=Ro(t.removed,`removed`);return{action:Eo(t.action),...P(`source`,n),...P(`scope`,r),...P(`removed`,i),packages:M(wo)(t.packages)}}function wo(e){let t=D(e);return{source:O(t,`source`),scope:To(t.scope),filtered:j(t,`filtered`),...P(`installedPath`,k(t,`installedPath`))}}function To(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function Eo(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Do(e){let t=D(e);return{packages:M(Oo)(t.packages),totals:jo(t.totals),diagnostics:M(Po)(t.diagnostics)}}function Oo(e){let t=D(e);return{source:O(t,`source`),scope:ko(t.scope),filtered:j(t,`filtered`),disabled:j(t,`disabled`),...P(`installedPath`,k(t,`installedPath`)),...P(`packageName`,k(t,`packageName`)),...P(`version`,k(t,`version`)),...P(`configuredVersion`,k(t,`configuredVersion`)),counts:jo(t.counts),resources:M(Mo)(t.resources),status:Ao(t.status)}}function ko(e){if(e!==`global`&&e!==`project`)throw Error(`Invalid Pi package plugin scope`);return e}function Ao(e){if(e!==`loaded`&&e!==`installed`&&e!==`missing`&&e!==`disabled`)throw Error(`Invalid Pi package plugin status`);return e}function jo(e){let t=D(e);return{extensions:A(t,`extensions`),skills:A(t,`skills`),prompts:A(t,`prompts`),themes:A(t,`themes`)}}function Mo(e){let t=D(e);return{kind:No(t.kind),name:O(t,`name`),path:O(t,`path`),relativePath:O(t,`relativePath`)}}function No(e){if(e!==`extension`&&e!==`skill`&&e!==`prompt`&&e!==`theme`)throw Error(`Invalid Pi package plugin resource kind`);return e}function Po(e){let t=D(e),n=t.type;if(n!==`warning`&&n!==`error`)throw Error(`Invalid Pi package plugin diagnostic type`);return{type:n,message:O(t,`message`),...P(`source`,k(t,`source`)),...P(`path`,k(t,`path`))}}function Fo(e){let t=D(e);return{plugins:M(Io)(t.plugins)}}function Io(e){let t=D(e);return{id:O(t,`id`),module:O(t,`module`),source:O(t,`source`),scope:Lo(t.scope),machineSpecific:Ro(t.machineSpecific,`machineSpecific`)??!1,enabled:j(t,`enabled`)}}function Lo(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEBUI plugin scope`);return e}function Ro(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function zo(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:Vo(t.components),release:qo(t.release),commands:Jo(t.commands),messages:M(Yo)(t.messages)}}function Bo(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:Ho(t.components),capabilities:Zo(t.capabilities)}}function Vo(e){let t=D(e);return{web:Go(t.web),sessiond:Go(t.sessiond)}}function Ho(e){let t=D(e);return{web:Uo(t.web),sessiond:Uo(t.sessiond)}}function Uo(e){let t=D(e),n=Xo(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:vn(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);let a=t.sessiondListener,o=Wo(a);if(a!==void 0&&(n!==`sessiond`||o===void 0))throw Error(`Invalid session daemon listener descriptor`);return{component:n,label:O(t,`label`),...P(`runtimeVersion`,k(t,`runtimeVersion`)),available:j(t,`available`),capabilities:Zo(t.capabilities),...P(`activeAgentProfile`,i),...P(`sessiondListener`,o),...P(`error`,k(t,`error`))}}function Wo(e){if(e===void 0)return;if(!Bn(e)||Array.isArray(e))throw Error(`Invalid session daemon listener descriptor`);let t=e.kind;if(t===`socket`)return Nr(e,[`kind`],`session daemon listener descriptor`),{kind:`socket`};if(t!==`tcp`)throw Error(`Invalid session daemon listener descriptor`);Nr(e,[`kind`,`host`,`port`,`hostSource`,`portSource`],`session daemon listener descriptor`);let n=e.host,r=e.port,i=e.hostSource,a=e.portSource;if(typeof n!=`string`||n===``||typeof r!=`number`||!Number.isInteger(r)||r<1||r>65535||i!==`env`&&i!==`config`&&i!=="default"||a!==`env`&&a!==`config`)throw Error(`Invalid session daemon listener descriptor`);return{kind:`tcp`,host:n,port:r,hostSource:i,portSource:a}}function Go(e){let t=D(e);return{component:Xo(t.component),label:O(t,`label`),...P(`runtimeVersion`,k(t,`runtimeVersion`)),...P(`installedVersion`,k(t,`installedVersion`)),stale:j(t,`stale`),available:j(t,`available`),...P(`installation`,Ko(t.installation)),...P(`error`,k(t,`error`))}}function Ko(e){if(e===void 0)return;let t=D(e),n=O(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEBUI installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEBUI installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEBUI Docker mode`);return{kind:n,...P(`path`,k(t,`path`)),...P(`source`,k(t,`source`)),...r===void 0?{}:{scope:r},...P(`npmRoot`,k(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function qo(e){let t=D(e);return{packageName:O(t,`packageName`),...P(`latestVersion`,k(t,`latestVersion`)),updateAvailable:j(t,`updateAvailable`),...P(`checkedAt`,k(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...P(`error`,k(t,`error`))}}function Jo(e){let t=D(e);return{...P(`update`,k(t,`update`)),...P(`restart`,k(t,`restart`)),...P(`restartWeb`,k(t,`restartWeb`)),...P(`restartSessiond`,k(t,`restartSessiond`)),...P(`status`,k(t,`status`))}}function Yo(e){let t=D(e);return{id:O(t,`id`),severity:Qo(t.severity),title:O(t,`title`),body:O(t,`body`),...P(`command`,k(t,`command`))}}function Xo(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEBUI service component`);return e}function Zo(e){let t=Dn(e);if(t===void 0)throw Error(`Invalid PI WEBUI capabilities`);return t}function Qo(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEBUI status severity`);return e}function $o(e){let t=D(e),n=O(t,`type`);if(n===`unsupported`)return{type:n,message:O(t,`message`)};if(n===`select`)return{type:n,requestId:O(t,`requestId`),title:O(t,`title`),options:M(ls)(t.options)};if(n===`tree`)return{type:n,tree:es(t.tree)};if(n===`done`)return{type:n,...P(`message`,k(t,`message`)),...us(t.session),...P(`promptDraft`,k(t,`promptDraft`))};throw Error(`Invalid command result type`)}function es(e){let t=D(e),n=M(ts)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=os(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:cs(t.activePathIds,`activePathIds`)}}function ts(e){let t=D(e);return{id:ss(t,`id`),parentId:os(t,`parentId`),kind:ns(t.kind),summary:O(t,`summary`),...P(`timestamp`,k(t,`timestamp`)),...P(`label`,k(t,`label`))}}function ns(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`system`:case`compaction`:case`branch-summary`:case`context-edit`:case`usage`: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 rs(e){let t=D(e),n=j(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){as(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 as(t,`aborted`,`session tree navigation result`),{cancelled:n,...P(`editorText`,k(t,`editorText`))}}function is(e){let t=D(e);return j(t,`cancelled`)?(as(t,`session`,`session fork cancellation result`),{cancelled:!0}):{cancelled:!1,session:pr(t.session)}}function as(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function os(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 ss(e,t){let n=O(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function cs(e,t){let n=Yn(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function ls(e){let t=D(e);return{value:O(t,`value`),label:O(t,`label`),...P(`description`,k(t,`description`))}}function us(e){return e===void 0?{}:{session:pr(e)}}function ds(e){if(D(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function fs(e){let t=D(e);return M(ps)(t.attachments)}function ps(e){let t=D(e);return{path:O(t,`path`),mimeType:O(t,`mimeType`),size:A(t,`size`)}}function ms(e){if(D(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function hs(e){if(typeof e!=`string`)throw Error(`Expected string value`);return e}function gs(e){let t=D(e);return{closedProjectIds:M(hs)(t.closedProjectIds)}}function _s(e){if(D(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function vs(e){if(D(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function ys(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:Yn(t.sessionIds,`sessionIds`),r=N(t,`archivedCount`),i=N(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function bs(e){if(D(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function xs(e){if(D(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function Ss(e){if(D(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function Cs(e){if(D(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function ws(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEBUI ${t} field`);return n}}function N(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function Ts(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 P(e,t){return t===void 0?{}:{[e]:t}}function Es(e){let t=D(e),n=D(t.memory),r=D(t.network);return{generatedAt:O(t,`generatedAt`),memory:{totalBytes:A(n,`totalBytes`),usedBytes:A(n,`usedBytes`),freeBytes:A(n,`freeBytes`),usagePercent:A(n,`usagePercent`)},network:ks(r)}}function Ds(e){let t=D(e),n=D(t.os),r=D(t.cpu),i=D(t.memory),a=D(t.network),o=t.gpu,s;if(o!=null){let e=D(o),t={name:O(e,`name`)},n=k(e,`driverVersion`);n!==void 0&&(t.driverVersion=n);let r=N(e,`memoryTotalBytes`);r!==void 0&&(t.memoryTotalBytes=r);let i=N(e,`memoryUsedBytes`);i!==void 0&&(t.memoryUsedBytes=i);let a=N(e,`utilizationPercent`);a!==void 0&&(t.utilizationPercent=a);let c=N(e,`temperatureCelsius`);c!==void 0&&(t.temperatureCelsius=c),s=t}let c={generatedAt:O(t,`generatedAt`),os:{platform:O(n,`platform`),release:O(n,`release`),arch:O(n,`arch`),uptimeSeconds:A(n,`uptimeSeconds`)},cpu:{model:O(r,`model`),cores:A(r,`cores`),usagePercent:A(r,`usagePercent`)},memory:{totalBytes:A(i,`totalBytes`),usedBytes:A(i,`usedBytes`),freeBytes:A(i,`freeBytes`),usagePercent:A(i,`usagePercent`)},network:Os(a)};s!==void 0&&(c.gpu=s);let l=k(t,`piVersion`);l!==void 0&&(c.piVersion=l);let u=k(t,`piWebUiVersion`);return u!==void 0&&(c.piWebUiVersion=u),c}function Os(e){let t={hostname:O(e,`hostname`),localIpv4Addresses:Yn(e.localIpv4Addresses,`localIpv4Addresses`),...ks(e)},n=k(e,`publicIpv4`);n!==void 0&&(t.publicIpv4=n);let r=k(e,`publicIpv6`);return r!==void 0&&(t.publicIpv6=r),t}function ks(e){let t={},n=N(e,`downloadSpeedBytesPerSecond`);n!==void 0&&(t.downloadSpeedBytesPerSecond=n);let r=N(e,`uploadSpeedBytesPerSecond`);return r!==void 0&&(t.uploadSpeedBytesPerSecond=r),t}function As(e){let t=jr(e,`project usage count response`);return Nr(t,[`sessionCount`],`project usage count response`),{sessionCount:ri(t,`sessionCount`)}}function js(e){let t=D(e);return{input:A(t,`input`),output:A(t,`output`),cacheRead:A(t,`cacheRead`),cacheWrite:A(t,`cacheWrite`),cost:A(t,`cost`),sessionCount:A(t,`sessionCount`)}}function Ms(e){let t=D(e),n=D(t.buckets);return{projectPath:O(t,`projectPath`),buckets:{live:js(n.live),retired:js(n.retired),archived:js(n.archived)},total:js(t.total),generatedAt:O(t,`generatedAt`)}}function Ns(e){return typeof e==`string`?e:e.id}function Ps(e){return typeof e==`string`?void 0:e.cwd}function Fs(e,t,n,r){let i=new URLSearchParams;r?.path!==void 0&&i.set(`path`,r.path),r?.staged===!0&&i.set(`staged`,`true`);let a=i.toString();return`api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/git/diff${a?`?${a}`:``}`}function Is(e,t,n=`local`){let r=new URLSearchParams,i=Ps(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(Ns(e))}/messages${a===``?``:`?${a}`}`}function Ls(e,t=`local`){let n=new URLSearchParams,r=Ps(e);r!==void 0&&r!==``&&n.set(`cwd`,r);let i=n.toString();return`api/machines/${encodeURIComponent(t)}/sessions/${encodeURIComponent(Ns(e))}/export${i===``?``:`?${i}`}`}function Rs(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`),Jt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function zs(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),Jt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var F=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`,Bs=e=>e===void 0?void 0:{signal:e};function Vs(e){return typeof e==`string`?e:e.id}function Hs(e){return typeof e==`string`?void 0:e.cwd}function Us(e,t=`local`){return`${F(t)}/sessions/${encodeURIComponent(Vs(e))}`}function I(e,t,n=`local`){return`${Us(e,n)}/${t}`}function Ws(e,t,n=`local`){return`${I(e,t,n)}${Ks(e)}`}function Gs(e,t=`local`){return`${Us(e,t)}${Ks(e)}`}function Ks(e){let t=Hs(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function L(e,t={}){let n=Hs(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function qs(e){return JSON.stringify({sessions:e.map(Js)})}function Js(e){let t=Vs(e),n=Hs(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Ys(e){return e===`local`?`api/pi-webui/status`:`${F(e)}/pi-webui/status`}var Xs={piWebUiStatus:(e=`local`)=>T(Ys(e),zo),checkForUpdates:(e=`local`)=>T(`${Ys(e)}?refresh=1`,zo,{cache:`no-store`}),piWebUiRuntime:()=>T(`api/pi-webui/runtime`,Bo),systemInfo:(e=`local`)=>T(`${F(e)}/pi-webui/system-info`,Ds),systemMetrics:(e=`local`)=>T(`${F(e)}/pi-webui/system-metrics`,Es,{cache:`no-store`})},Zs={status:()=>T(`api/tts`,Vn,{cache:`no-store`}),speak:(e,t)=>T(`api/tts/speak`,Wn,{method:`POST`,body:JSON.stringify(e),...t===void 0?{}:{signal:t}}),stop:e=>T(`api/tts/stop`,Gn,{method:`POST`,body:JSON.stringify({runId:e})})},Qs={settings:()=>T(`api/speech-input/settings`,no,{cache:`no-store`}),saveSettings:e=>T(`api/speech-input/settings`,no,{method:`PUT`,body:JSON.stringify(e)}),transcribe:(e,t,n)=>T(`api/speech-input/transcribe`,Kn,{method:`POST`,body:e,headers:{"content-type":t},...n===void 0?{}:{signal:n}}),polish:async(e,t)=>{try{return await T(`api/speech-input/polish`,$s,{method:`POST`,body:JSON.stringify({text:e}),...t===void 0?{}:{signal:t}})}catch{throw Error(`Speech input polishing failed.`)}}};function $s(e){if(!Pc(e)||Array.isArray(e))throw Error(`Invalid speech input polishing response`);let t=Object.keys(e);if(t.length!==1||t[0]!==`text`)throw Error(`Invalid speech input polishing response`);let n=e.text;if(typeof n!=`string`||n.trim()===``||new TextEncoder().encode(n).byteLength>1048576)throw Error(`Invalid speech input polishing response`);return n}var ec={machines:()=>T(`api/machines`,nr),addMachine:e=>T(`api/machines`,rr,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>T(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>T(`api/machines/${encodeURIComponent(e)}/health`,ir),runtime:(e,t=!1)=>T(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,ar,t?{cache:`no-store`}:{})};function tc(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-memory/snapshot?${n.toString()}`}var nc={snapshot:(e,t=`local`)=>T(tc(e,t),Xn,{cache:`no-store`})};function rc(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-skills/snapshot?${n.toString()}`}var ic={snapshot:(e,t=`local`)=>T(rc(e,t),Qn,{cache:`no-store`})};function ac(e){return e===void 0?`api/config`:`${F(e)}/config`}function oc(e){return e===void 0?`api/plugins`:`${F(e)}/plugins`}var sc={config:e=>T(ac(e),to),saveConfig:(e,t)=>T(ac(t),to,{method:`PUT`,body:JSON.stringify({config:e})})},cc={plugins:e=>T(oc(e),Fo)};function lc(e=`local`){return`${F(e)}/models-config`}var uc={config:(e=`local`)=>T(lc(e),Ci),limitsStatus:(e=`local`)=>T(`${lc(e)}/limits`,Mi),save:async(e,t=`local`)=>{let{status:n,body:r}=await $t(lc(t),{method:`PUT`,body:JSON.stringify(e)});if(n<200||n>=300)throw sn(r,n,`Failed to save models configuration.`);return ji(r)},test:(e,t=`local`)=>T(`${lc(t)}/test`,Fi,{method:`POST`,body:JSON.stringify(e)}),discover:(e,t=`local`)=>T(`${lc(t)}/discover`,Ni,{method:`POST`,body:JSON.stringify(e)})};function dc(e=`local`){return`${F(e)}/model-tiers`}var fc={settings:(e=`local`)=>T(dc(e),Ga),save:(e,t=`local`)=>T(dc(t),Ga,{method:`PUT`,body:JSON.stringify({ladder:e})})};function pc(e=`local`){return`${F(e)}/utility-models`}function mc(e,t){if(t!==1)return e;let n={};if(Object.prototype.hasOwnProperty.call(e,`lightweight`)){let t=e.lightweight;t!==void 0&&(n.lightweight=t===null?null:hc(t))}if(Object.prototype.hasOwnProperty.call(e,`context`)){let t=e.context;if(t===`session`)throw Error(`Cannot save the session-only Context model to a contract version 1 runtime`);t!==void 0&&(n.context=t===null?null:hc(t))}return n}function hc(e){return{provider:e.provider,id:e.id}}var gc={settings:(e=`local`)=>T(pc(e),Aa),save:(e,t,n=`local`)=>T(pc(n),Aa,{method:`PUT`,body:JSON.stringify({settings:mc(e,t)})})};function _c(e=`local`){return`${F(e)}/skills`}function vc(e,t=`local`){return`${_c(t)}?${new URLSearchParams({cwd:e}).toString()}`}var yc={list:(e,t=`local`)=>T(vc(e,t),Ii),toggle:(e,t=`local`)=>T(_c(t),Bi,{method:`PATCH`,body:JSON.stringify(e)}),search:(e,t=`local`)=>T(`${_c(t)}/search`,Vi,{method:`POST`,body:JSON.stringify(e)}),install:(e,t=`local`)=>T(`${_c(t)}/install`,Bi,{method:`POST`,body:JSON.stringify(e)}),check:(e,t=`local`)=>T(`${_c(t)}/check`,Ui,{method:`POST`,body:JSON.stringify(e)}),update:(e,t=`local`)=>T(`${_c(t)}/update`,Ki,{method:`POST`,body:JSON.stringify(e)})};function bc(e=``,t){let n=t===void 0?`api/pi-packages`:`${F(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var xc={packages:e=>T(bc(``,e),So),install:(e,t)=>{let n={source:e};return T(bc(`install`,t),Co,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return T(bc(`remove`,n),Co,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return T(bc(`update`,t),Co,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}};function Sc(e=`local`){return`${F(e)}/package-plugins`}function Cc(e,t=`local`){return`${Sc(t)}?${new URLSearchParams({cwd:e}).toString()}`}var wc={list:(e,t=`local`)=>T(Cc(e,t),Do),mutate:(e,t=`local`)=>T(Sc(t),Do,{method:`POST`,body:JSON.stringify(e)})},Tc={workspaceActivity:(e=`local`)=>T(`${F(e)}/activity`,ka)},Ec={projects:(e=`local`)=>T(`${F(e)}/projects`,M(cr)),addProject:(e,t,n,r=`local`)=>T(`${F(r)}/projects`,cr,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}`,ms,{method:`DELETE`}),closeProjectTree:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/close-tree`,gs,{method:`POST`}),pinProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/pin`,M(cr),{method:`POST`}),unpinProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/unpin`,M(cr),{method:`POST`}),projectDirectories:(e,t=`local`)=>T(`${F(t)}/project-directories?q=${encodeURIComponent(e)}`,M(fa)),projectUsageCount:(e,t=`local`)=>T(`${F(t)}/sessions/project-usage/count`,As,{method:`POST`,body:JSON.stringify(e)}),projectUsage:(e,t=`local`)=>T(`${F(t)}/sessions/project-usage`,Ms,{method:`POST`,body:JSON.stringify(e)})},Dc={recentProjects:(e=`local`)=>T(`${F(e)}/recent-projects`,ur),recordRecentProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/recent`,ur,{method:`POST`}),removeRecentProject:(e,t=`local`)=>T(`${F(t)}/recent-projects/${encodeURIComponent(e)}`,ur,{method:`DELETE`})},Oc={workspaces:(e,t=`local`,n)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/workspaces`,M(dr),Bs(n)),deleteWorkspace:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Ta,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,pa),workspaceFile:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,ha),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 T(`${F(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,ga,{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 T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,_a,{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`),T(`${F(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,va,{method:`POST`})}},kc={sessions:(e,t=`local`,n)=>T(`${F(t)}/sessions?cwd=${encodeURIComponent(e)}`,M(pr),Bs(n)),reorder:(e,t,n=`local`)=>T(I(e,`reorder`,n),hr,{method:`POST`,body:JSON.stringify(t)}),unreadCatalog:(e=`local`)=>T(`${F(e)}/sessions/unread`,Rr,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return T(I(e,`unread/acknowledge`,r),Rr,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>T(Ws(e,`notifications`,t),Gr),dismissNotification:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss`,r),Gr,{method:`POST`,body:L(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss-all`,r),Gr,{method:`POST`,body:L(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>T(`${F(t)}/sessions`,pr,{method:`POST`,body:JSON.stringify({cwd:e,...n===void 0?{}:{modelPolicy:n}})}),startPlusSession:(e,t,n=`local`)=>T(`${F(n)}/sessions`,pr,{method:`POST`,body:JSON.stringify({cwd:e,creationSource:`session-list-plus`,initialModelPolicy:t})}),sessionDefaults:(e,t=`local`)=>T(`${F(t)}/session-defaults?cwd=${encodeURIComponent(e)}`,xi),sessionDefaultsV2:(e,t=`local`)=>{let n=new URLSearchParams({cwd:e,starterModelPolicyContract:`2`});return T(`${F(t)}/session-defaults?${n.toString()}`,Si)},updateSessionDefaults:(e,t,n=`local`)=>T(`${F(n)}/session-defaults`,xi,{method:`PUT`,body:JSON.stringify({cwd:e,...t})}),cleanupPreview:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup/preview`,ci,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup`,li,{method:`POST`,body:JSON.stringify(e)}),forceCleanup:(e=`local`)=>T(`${F(e)}/sessions/cleanup/force`,li,{method:`POST`}),archiveMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/archive`,ui,{method:`POST`,body:qs(e)}),deleteArchivedMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/delete-archived`,di,{method:`POST`,body:qs(e)}),messages:(e,t,n=`local`,r)=>T(Is(e,t,n),tr,Bs(r)),status:(e,t=`local`,n)=>T(Ws(e,`status`,t),br,Bs(n)),systemPrompt:(e,t=`local`)=>T(Ws(e,`system-prompt`,t),Fr),extensionEntries:(e,t=`local`,n)=>T(Ws(e,`extension-entries`,t),Lr,Bs(n)),streamSnapshot:(e,t=`local`,n)=>T(Ws(e,`stream-snapshot`,t),Pr,Bs(n)),clearQueue:(e,t=`local`)=>T(I(e,`queue/clear`,t),br,{method:`POST`,body:L(e)}),dismissWarning:(e,t,n=`local`)=>T(I(e,`warnings/dismiss`,n),br,{method:`POST`,body:L(e,{dismissId:t})}),modelPolicy:(e,t=`local`)=>T(Ws(e,`model-policy`,t),xr),rememberCurrentModelPolicy:(e,t=`local`)=>T(Ws(e,`model-policy/remember`,t),Tr,{method:`POST`}),setModelPolicy:(e,t,n=`local`)=>T(I(e,`model-policy`,n),xr,{method:`PUT`,body:L(e,{policy:t})}),models:(e,t=`local`)=>T(Ws(e,`models`,t),bi),setModel:(e,t,n,r=`local`)=>T(I(e,`model`,r),br,{method:`POST`,body:L(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>T(I(e,`model/cycle`,n),br,{method:`POST`,body:L(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>T(Ws(e,`thinking-levels`,t),Ji),setThinkingLevel:(e,t,n=`local`)=>T(I(e,`thinking-level`,n),br,{method:`POST`,body:L(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>T(I(e,`thinking-level/cycle`,t),br,{method:`POST`,body:L(e)}),commands:(e,t=`local`)=>T(Ws(e,`commands`,t),M(da)),prompt:(e,t,n,r=`local`,i)=>T(I(e,`prompt`,r),ds,{method:`POST`,body:L(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>T(I(e,`attachments`,n),fs,{method:`POST`,body:L(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>T(I(e,`shell`,n),ds,{method:`POST`,body:L(e,{text:t})}),runCommand:(e,t,n=`local`)=>T(I(e,`commands/run`,n),$o,{method:`POST`,body:L(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>T(I(e,`commands/respond`,r),$o,{method:`POST`,body:L(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>T(I(e,`tree/navigate`,n),rs,{method:`POST`,body:L(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),editFromHere:(e,t,n=`local`)=>T(I(e,`messages/edit-from-here`,n),rs,{method:`POST`,body:L(e,{entryId:t})}),forkFromHere:(e,t,n=`local`)=>T(I(e,`messages/fork`,n),is,{method:`POST`,body:L(e,{entryId:t})}),abort:(e,t=`local`)=>T(I(e,`abort`,t),_s,{method:`POST`,body:L(e)}),stop:(e,t=`local`)=>T(I(e,`stop`,t),vs,{method:`POST`,body:L(e)}),archive:(e,t=`local`)=>T(I(e,`archive`,t),ys,{method:`POST`,body:L(e)}),archiveWithDescendants:(e,t=`local`)=>T(I(e,`archive-tree`,t),ys,{method:`POST`,body:L(e)}),restore:(e,t=`local`)=>T(I(e,`restore`,t),bs,{method:`POST`,body:L(e)}),deleteArchived:(e,t=`local`)=>T(Gs(e,t),xs,{method:`DELETE`}),detachParent:(e,t=`local`)=>T(I(e,`detach-parent`,t),Ss,{method:`POST`,body:L(e)}),reloadSession:(e,t=`local`)=>T(I(e,`reload`,t),Cs,{method:`POST`,body:L(e)}),pin:(e,t=`local`)=>T(I(e,`pin`,t),pr,{method:`POST`,body:L(e)}),unpin:(e,t=`local`)=>T(I(e,`unpin`,t),pr,{method:`POST`,body:L(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 T(`${F(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,$i)},saveApiKey:(e,t,n=`local`)=>T(`${F(n)}/auth/api-key`,ds,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>T(`${F(t)}/auth/api-key/interactive`,ea,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>T(`${F(t)}/auth/logout`,ds,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>T(`${F(t)}/auth/oauth`,ea,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}`,ea),respondOAuthFlow:(e,t,n,r=`local`)=>T(`${F(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,ea,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ea,{method:`POST`})},Ac={terminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,M(wa)),startTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,wa,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ms,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,ms,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,wa,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Ta,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>T(`${F(t)}/terminal-command-runs${Mc(e)}`,M(Ta)),getCommandRun:(e,t=`local`)=>jc(e,t),cancelCommandRun:(e,t=`local`)=>T(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Ta,{method:`POST`})};async function jc(e,t){let n=await fetch(Jt(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(Nc(e)??n.statusText)}return Ta(await n.json())}}function Mc(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 Nc(e){if(!Pc(e))return;let t=e.error;return typeof t==`string`?t:void 0}function Pc(e){return typeof e==`object`&&!!e}var Fc={files:(e,t,n={})=>{let r=new URLSearchParams({q:t});return n.kind!==void 0&&r.set(`kind`,n.kind),n.mode!==void 0&&r.set(`mode`,n.mode),n.scope!==void 0&&r.set(`scope`,n.scope),n.workspaceScoped===!0&&n.projectId!==void 0&&n.workspaceId!==void 0?T(`${F(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,M(fa)):(r.set(`cwd`,e),T(`${F(n.machineId)}/files?${r.toString()}`,M(fa)))}},Ic={gitStatus:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,ba),gitDiff:(e,t,n,r=`local`)=>T(Fs(r,e,t,n),Ca)},Lc={...Xs,...Zs,...ec,...nc,learnedSkills:ic,...fc,utilityModels:gc,...sc,...cc,...xc,...wc,...Tc,...Ec,...Dc,...Oc,...kc,...Ac,...Fc,...Ic};function Rc(e,t=`local`){let n=typeof e==`string`?void 0:e.cwd,r=n===void 0||n===``?``:`?${new URLSearchParams({cwd:n}).toString()}`,i=typeof e==`string`?e:e.id;return new WebSocket(Yt(`${Vc(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function zc(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(`${Vc(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function Bc(e=`local`){return new WebSocket(Yt(`${Vc(e)}/events`))}function Vc(e){return`api/machines/${encodeURIComponent(e)}`}var Hc=512*1024,Uc=/^[a-z][a-z0-9.-]*$/u;function Wc(e){if(!sl(e))return ol(`Config must be an object`);if(e.version!==1)return ol(`Config version must be 1`);let t=e.tasks;if(!Array.isArray(t))return ol(`Config tasks must be an array`);let n=new Set,r=[];for(let[e,i]of t.entries()){let t=$c(i,e);if(!t.ok)return t;if(n.has(t.task.id))return ol(`Duplicate task id: ${t.task.id}`);n.add(t.task.id),r.push(t.task)}return{ok:!0,config:{version:1,tasks:r}}}function Gc(e){let t={version:e.version,tasks:e.tasks.map(e=>({id:e.id,title:e.title,command:e.command,...e.description===void 0?{}:{description:e.description},...e.group===void 0?{}:{group:e.group},confirm:e.confirm}))};return`${JSON.stringify(t,null,2)}\n`}function Kc(e){return new TextEncoder().encode(Gc(e)).byteLength}function qc(e){let t=Kc(e);if(t>524288)throw RangeError(`Workspace tasks catalog is ${String(t)} bytes; maximum is ${String(Hc)} bytes`)}function Jc(e){return Uc.test(e)}function Yc(e,t){return{version:e.version,tasks:[...e.tasks,t]}}function Xc(e,t,n){return nl(e,t),{version:e.version,tasks:[...e.tasks.slice(0,t),n,...e.tasks.slice(t+1)]}}function Zc(e,t){return nl(e,t),{version:e.version,tasks:[...e.tasks.slice(0,t),...e.tasks.slice(t+1)]}}function Qc(e){if(rl(e.source.ref.scope),il(e.source.ref.id),rl(e.destination.scope),il(e.destination.task.id),e.source.ref.scope===e.destination.scope)throw Error(`Workspace task moves must cross scopes`);let t=e.source.config.tasks.findIndex(t=>t.id===e.source.ref.id);if(t===-1)throw Error(`Source workspace task not found: ${e.source.ref.id}`);if(e.destination.config.tasks.some(t=>t.id===e.destination.task.id))throw Error(`Destination workspace task already exists: ${e.destination.task.id}`);let n=Zc(e.source.config,t),r=Yc(e.destination.config,e.destination.task);return qc(n),qc(r),{sourceAfter:n,destinationAfter:r}}function $c(e,t){let n=`Task ${String(t+1)}`;if(!sl(e))return ol(`${n} must be an object`);let r=el(e,`id`,n);if(!r.ok)return r;if(!Jc(r.value))return ol(`${n} id must match ${Uc.source}`);let i=el(e,`title`,n);if(!i.ok)return i;let a=el(e,`command`,n);if(!a.ok)return a;let o=tl(e,`description`,n);if(!o.ok)return o;let s=tl(e,`group`,n);if(!s.ok)return s;let c=e.confirm;return c!==void 0&&typeof c!=`boolean`?ol(`${n} confirm must be a boolean`):{ok:!0,task:{id:r.value,title:i.value,command:a.value,...o.value===void 0?{}:{description:o.value},...s.value===void 0?{}:{group:s.value},confirm:c??!1}}}function el(e,t,n){let r=e[t];return typeof r!=`string`||r.trim()===``?ol(`${n} ${t} must be a non-empty string`):{ok:!0,value:r}}function tl(e,t,n){let r=e[t];return r===void 0?{ok:!0,value:void 0}:typeof r!=`string`||r.trim()===``?ol(`${n} ${t} must be a non-empty string when provided`):{ok:!0,value:r}}function nl(e,t){if(!Number.isInteger(t)||t<0||t>=e.tasks.length)throw RangeError(`Task index ${String(t)} is out of range`)}function rl(e){if(!al(e))throw Error(`Invalid workspace task scope: ${String(e)}`)}function il(e){if(typeof e!=`string`||!Jc(e))throw Error(`Invalid workspace task id: ${String(e)}`)}function al(e){return e===`global`||e===`workspace`}function ol(e){return{ok:!1,error:e}}function sl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var cl=new Set([`source-changed`,`destination-collision`,`invalid-catalog`,`unrecognized-state`,`unowned-intermediate-state`,`move-in-progress`,`retry-pristine`]),ll=new Set([`revision-conflict`,`invalid-catalog`,`move-in-progress`,`move-recovery-pending`,`unowned-intermediate-state`]);function ul(e){switch(Tl(e,[`kind`,`config`,`revision`,`message`,`hint`,`detail`],`workspace tasks catalog response`).kind){case`loaded`:{let t=Tl(e,[`kind`,`config`,`revision`],`workspace tasks loaded response`);return{kind:`loaded`,config:ml(t.config,`workspace tasks loaded catalog`),revision:gl(t,`revision`,`workspace tasks loaded response`)}}case`missing`:{let t=Tl(e,[`kind`,`message`,`hint`,`revision`],`workspace tasks missing response`);return{kind:`missing`,message:xl(t,`message`,`workspace tasks missing response`),hint:xl(t,`hint`,`workspace tasks missing response`),revision:gl(t,`revision`,`workspace tasks missing response`)}}case`invalid`:{let t=Tl(e,[`kind`,`message`,`hint`,`detail`],`workspace tasks invalid response`);return{kind:`invalid`,message:xl(t,`message`,`workspace tasks invalid response`),hint:xl(t,`hint`,`workspace tasks invalid response`),detail:xl(t,`detail`,`workspace tasks invalid response`)}}case`unavailable`:{let t=Tl(e,[`kind`,`message`,`hint`,`detail`],`workspace tasks unavailable response`),n=Sl(t,`workspace tasks unavailable response`);return{kind:`unavailable`,message:xl(t,`message`,`workspace tasks unavailable response`),hint:xl(t,`hint`,`workspace tasks unavailable response`),...n===void 0?{}:{detail:n}}}default:throw El(`workspace tasks catalog response`)}}function dl(e){switch(Tl(e,[`kind`,`config`,`revision`,`message`,`hint`,`detail`],`global workspace tasks response`).kind){case`loaded`:{let t=Tl(e,[`kind`,`config`,`revision`],`global workspace tasks loaded response`);return{kind:`loaded`,config:ml(t.config,`global workspace tasks loaded catalog`),revision:gl(t,`revision`,`global workspace tasks loaded response`)}}case`invalid`:{let t=Tl(e,[`kind`,`message`,`hint`,`detail`],`global workspace tasks invalid response`);return{kind:`invalid`,message:xl(t,`message`,`global workspace tasks invalid response`),hint:xl(t,`hint`,`global workspace tasks invalid response`),detail:xl(t,`detail`,`global workspace tasks invalid response`)}}default:throw El(`global workspace tasks response`)}}function fl(e){switch(Tl(e,[`kind`,`operationId`,`phase`,`workspace`,`global`,`reason`,`message`],`workspace task move result`).kind){case`completed`:{let t=Tl(e,[`kind`,`operationId`,`workspace`,`global`],`workspace task completed result`);return{kind:`completed`,operationId:hl(t,`operationId`,`workspace task completed result`),workspace:ul(t.workspace),global:dl(t.global)}}case`partial`:{let t=Tl(e,[`kind`,`operationId`,`phase`,`workspace`,`global`],`workspace task partial result`);if(t.phase!==`destination-written`)throw El(`workspace task partial result`);return{kind:`partial`,operationId:hl(t,`operationId`,`workspace task partial result`),phase:`destination-written`,workspace:ul(t.workspace),global:dl(t.global)}}case`conflict`:{let t=Tl(e,[`kind`,`reason`,`message`],`workspace task move conflict result`);return{kind:`conflict`,reason:_l(t.reason),message:xl(t,`message`,`workspace task move conflict result`)}}case`validation`:return{kind:`validation`,message:xl(Tl(e,[`kind`,`message`],`workspace task move validation result`),`message`,`workspace task move validation result`)};case`unavailable`:return{kind:`unavailable`,message:xl(Tl(e,[`kind`,`message`],`workspace task move unavailable result`),`message`,`workspace task move unavailable result`)};case`unknown-outcome`:return{kind:`unknown-outcome`,message:xl(Tl(e,[`kind`,`message`],`workspace task move unknown-outcome result`),`message`,`workspace task move unknown-outcome result`)};default:throw El(`workspace task move result`)}}function pl(e){switch(Tl(e,[`kind`,`reason`,`message`,`retryable`],`workspace tasks failure response`).kind){case`validation`:return{kind:`validation`,message:xl(Tl(e,[`kind`,`message`],`workspace tasks validation failure`),`message`,`workspace tasks validation failure`)};case`conflict`:{let t=Tl(e,[`kind`,`reason`,`message`],`workspace tasks conflict failure`);return{kind:`conflict`,reason:vl(t.reason),message:xl(t,`message`,`workspace tasks conflict failure`)}}case`unavailable`:{let t=Tl(e,[`kind`,`message`,`retryable`],`workspace tasks unavailable failure`);return{kind:`unavailable`,message:xl(t,`message`,`workspace tasks unavailable failure`),retryable:Cl(t,`retryable`,`workspace tasks unavailable failure`)}}case`unknown-outcome`:return{kind:`unknown-outcome`,message:xl(Tl(e,[`kind`,`message`],`workspace tasks unknown-outcome failure`),`message`,`workspace tasks unknown-outcome failure`)};default:throw El(`workspace tasks failure response`)}}function ml(e,t){let n=Wc(e);if(!n.ok)throw El(t);try{qc(n.config)}catch{throw El(t)}return n.config}function hl(e,t,n){let r=wl(e,t,n);if(!kn(r))throw El(n);return r}function gl(e,t,n){return wl(e,t,n)}function _l(e){if(!yl(e))throw El(`workspace task move conflict result`);return e}function vl(e){if(!bl(e))throw El(`workspace tasks conflict failure`);return e}function yl(e){return typeof e==`string`&&cl.has(e)}function bl(e){return typeof e==`string`&&ll.has(e)}function xl(e,t,n){return wl(e,t,n)}function Sl(e,t){if(Object.hasOwn(e,`detail`))return wl(e,`detail`,t)}function Cl(e,t,n){let r=e[t];if(typeof r!=`boolean`)throw El(n);return r}function wl(e,t,n){let r=e[t];if(typeof r!=`string`||r.trim()===``)throw El(n);return r}function Tl(e,t,n){if(!Dl(e)||Reflect.ownKeys(e).some(e=>typeof e!=`string`||!t.includes(e)))throw El(n);return e}function El(e){return Error(`Invalid ${e}`)}function Dl(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Reflect.getPrototypeOf(e);return t===Object.prototype||t===null}var Ol=`Workspace Tasks are unavailable on the selected machine.`,kl=`Workspace Tasks could not be loaded. Refresh and try again.`,Al=`Workspace task write outcome is unknown. Refresh before trying again.`,jl={readWorkspace(e,t){return Ml(Wl(e),ul,t)},replaceWorkspace(e){return Nl(Wl(e),{expectedRevision:e.expectedRevision,config:e.config},ul)},readGlobal(e,t){return Ml(Kl(e),dl,t)},replaceGlobal(e){return Nl(Kl(e.machineId),{expectedRevision:e.expectedRevision,config:e.config},dl)},move(e){return Pl(Gl(e),{operationId:e.operationId,intent:e.intent,source:e.source,destination:e.destination})}};async function Ml(e,t,n){try{return Fl(await $t(e,Vl(n)),t)}catch(e){if(n?.aborted===!0||Hl(e))throw e;return ql()}}async function Nl(e,t,n){try{return Il(await $t(e,{method:`PUT`,body:JSON.stringify(t)}),n)}catch{return Yl()}}async function Pl(e,t){try{return Ll(await $t(e,{method:`POST`,body:JSON.stringify(t)}))}catch{return Xl()}}function Fl(e,t){return e.status===200?{kind:`success`,value:t(e.body)}:e.status===404?Jl():Rl(e,ql)}function Il(e,t){return e.status===200?{kind:`success`,value:t(e.body)}:e.status===404?Jl():Rl(e,Yl)}function Ll(e){if(e.status===404)return{kind:`unavailable`,message:Ol};switch(e.status){case 200:return Bl(e.body,[`completed`]);case 400:case 413:return Bl(e.body,[`validation`]);case 409:return Bl(e.body,[`partial`,`conflict`]);case 500:return Bl(e.body,[`unknown-outcome`]);case 503:return Bl(e.body,[`unavailable`]);default:return Xl()}}function Rl(e,t){let n=zl(e.status);if(n===void 0)return t();let r=pl(e.body);return r.kind===n?r:t()}function zl(e){switch(e){case 400:case 413:return`validation`;case 409:return`conflict`;case 500:return`unknown-outcome`;case 503:return`unavailable`;default:return}}function Bl(e,t){let n=fl(e);return t.includes(n.kind)?n:Xl()}function Vl(e){return e===void 0?void 0:{signal:e}}function Hl(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`}function Ul(e){return`api/machines/${encodeURIComponent(e)}`}function Wl(e){return`${Ul(e.machineId)}/projects/${encodeURIComponent(e.projectId)}/workspaces/${encodeURIComponent(e.workspaceId)}/workspace-tasks`}function Gl(e){return`${Wl(e)}/move`}function Kl(e){return`${Ul(e)}/workspace-tasks/global`}function ql(){return{kind:`unavailable`,message:kl,retryable:!0}}function Jl(){return{kind:`unavailable`,message:Ol,retryable:!1}}function Yl(){return{kind:`unknown-outcome`,message:Al}}function Xl(){return{kind:`unknown-outcome`,message:Al}}var Zl=`.pi-webui/uploads`,Ql=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},$l=class extends Error{constructor(e,t){super(uu(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function eu(e){return e?.uploads?.defaultFolder??`.pi-webui/uploads`}function tu(e,t){return e?.uploads?.defaultFolder??t}function nu(e,t){let n=pu(e,`upload destination`,{allowEmpty:!0}),r=pu(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function ru(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`,Rs(e,t,n.path,ou(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(su(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(ga(hu(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(gu(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new Ql(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function iu(e,t,n,r={}){let i=r.destinationFolder??`.pi-webui/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:nu(i,e.name),loaded:0,total:e.size,percent:lu(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(cu(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 Ql;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=ru(e,t,{path:p.path,file:f},{...au(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(fu(e,c))throw e;let t=du(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 $l(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function au(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 ou(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function su(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:lu(e.loaded,n),lengthComputable:e.lengthComputable}}function cu(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:lu(i,r),done:n}}function lu(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function uu(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function du(e){return e instanceof Error?e.message:String(e)}function fu(e,t){return t.requested||e instanceof Ql}function pu(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(mu(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 mu(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function hu(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function gu(e){let t=_u(e);return vu(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function _u(e){try{return hu(e)}catch{return}}function vu(e){return typeof e==`object`&&!!e}function yu(e){return e.closesActionPalette===!0}function bu(e){return{mode:e.mode,exact:$u(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function xu(e){let t=Su(e);if(t.mode!==`tiered`||t.tier!==void 0)return t;let n=e.catalog?.rows;return n===void 0||!Object.hasOwn(n,`standard`)||!n.standard.valid?t:{...t,tier:`standard`}}function Su(e){if(e.policy!==void 0)return bu(e.policy);let t=e.liveResolved;return t===void 0?{mode:`exact`,exact:{model:{provider:``,id:``},thinkingLevel:``}}:{mode:`exact`,exact:$u(t)}}function Cu(e){let t=e.model?.provider,n=e.model?.id;if(!(t===void 0||n===void 0||!Qu(t)||!Qu(n))&&Qu(e.thinkingLevel))return{model:{provider:t,id:n},thinkingLevel:e.thinkingLevel}}function wu(e){let t=Cu(e)??Uu(),n=e.starterModelPolicyPreference;return Bu(e)?Vu(n)?{mode:n.mode,exact:$u(n.exact),...n.tier===void 0?{}:{tier:n.tier}}:n===void 0?{mode:`tiered`,exact:$u(t),tier:`standard`}:zu(n,t,n.mode):zu(n,t,`exact`)}function Tu(e,t){let n=Cu(t);return n===void 0||e.mode===`tiered`||Du(e.exact,n)?e:{...e,exact:$u(n)}}function Eu(e){if(!(e.mode===`tiered`&&e.tier===void 0))return{mode:e.mode,...e.tier===void 0?{}:{tier:e.tier}}}function Du(e,t){return e.model.provider===t.model.provider&&e.model.id===t.model.id&&e.thinkingLevel===t.thinkingLevel}function Ou(e,t){return{...e,mode:`tiered`,tier:t}}function ku(e){return{...e,mode:`exact`}}function Au(e,t){let n=t.thinkingLevels.includes(e.exact.thinkingLevel)?e.exact.thinkingLevel:``;return{...e,exact:{model:{...t.model},thinkingLevel:n}}}function ju(e,t){return{...e,exact:{...e.exact,thinkingLevel:t}}}function Mu(e,t){if(e.mode===`exact`)return Iu(e.exact,t.models)?{mode:`exact`,exact:$u(e.exact)}:void 0;let n=e.tier;if(!(n===void 0||!t.valid||!Yu(t)||!Xu(t,n)))return{mode:`tiered`,tier:n}}function Nu(e,t){return t!==void 0&&Mu(e,t)!==void 0}function Pu(e,t,n){let r=Wu(e);if(Hu(t)||e.mode!==`tiered`||Ku(e.exact)||!qu(e.tier)||!Yu(n)||!Xu(n,e.tier))return r;let i=n.ladder?.[e.tier];return i===void 0||!Ku(i)?r:{...r,exact:$u(i)}}function Fu(e,t){let n=e.mode===`exact`?Lu(e.exact,t):Ru(e,t);if(n.kind===`blocked`)return n;let r=Gu(e.exact);return r===void 0?{kind:`ready`,initialModelPolicy:{mode:e.mode,exact:$u(e.exact),...e.tier===void 0?{}:{tier:e.tier}},resolved:$u(n.resolved)}:{kind:`blocked`,reason:r}}function Iu(e,t){return Gu(e)===void 0&&t.find(t=>Zu(t.model,e.model))?.thinkingLevels.includes(e.thinkingLevel)===!0}function Lu(e,t){let n=Gu(e);if(n!==void 0)return{kind:`blocked`,reason:n};let r=t.models.find(t=>Zu(t.model,e.model));return r===void 0?{kind:`blocked`,reason:`Selected provider/model is unavailable`}:r.thinkingLevels.includes(e.thinkingLevel)?{kind:`ready`,resolved:$u(e)}:{kind:`blocked`,reason:`Selected thinking level is unsupported by the selected model`}}function Ru(e,t){let n=e.tier;if(!qu(n))return{kind:`blocked`,reason:Ju(void 0,t)};let r=Object.hasOwn(t.rows,n)?t.rows[n]:void 0;if(r?.valid!==!0)return{kind:`blocked`,reason:Ju(r,t)};let i=t.ladder?.[n];return i===void 0||!Ku(i)?{kind:`blocked`,reason:Ju(r,t)}:{kind:`ready`,resolved:$u(i)}}function zu(e,t,n){return{mode:e?.mode??n,exact:$u(t),...e?.tier===void 0?{}:{tier:e.tier}}}function Bu(e){return`starterModelPolicyContractVersion`in e}function Vu(e){return e!==void 0&&Object.hasOwn(e,`exact`)}function Hu(e){return Bu(e)&&Vu(e.starterModelPolicyPreference)}function Uu(){return{model:{provider:``,id:``},thinkingLevel:``}}function Wu(e){return{mode:e.mode,exact:$u(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function Gu(e){return Ku(e)?void 0:`Choose a provider, model, and thinking level before starting`}function Ku(e){return Qu(e.model.provider)&&Qu(e.model.id)&&Qu(e.thinkingLevel)}function qu(e){return e!==void 0&&Bt.includes(e)}function Ju(e,t){return e?.reason!==void 0&&Qu(e.reason)?e.reason:t.configError!==void 0&&Qu(t.configError)?t.configError:`Selected model tier is unavailable`}function Yu(e){let t=e.ladder;return t!==void 0&&Bt.every(e=>Object.hasOwn(t,e))}function Xu(e,t){return Object.hasOwn(e.rows,t)&&e.rows[t].valid}function Zu(e,t){return e.provider===t.provider&&e.id===t.id}function Qu(e){return e.trim()!==``}function $u(e){return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function ed(e){return{kind:`policy-blocked`,scope:e}}function td(e,t,n){return{kind:e,message:t,scope:n}}function nd(e,t){return{kind:`policy-fallback`,message:e,scope:t}}function rd(e,t,n){if(e===void 0||!ad(e,t))return;let r=e.kind===`policy-blocked`?n:e.message;return r===void 0||r===``?void 0:r}function id(e,t,n){return ad(e,t)?e.kind!==`policy-blocked`||n!==void 0&&n!==``:!1}function ad(e,t){return t!==void 0&&e.scope.machineId===t.machineId&&e.scope.workspaceId===t.workspaceId}var od=`The session may start with the Lightweight utility model.`;function sd(e){return Ku(e.exact)&&(e.mode===`exact`||qu(e.tier))}function cd(e){if(!sd(e))throw Error(`Cannot build a complete starter model policy from an incomplete draft`);return{mode:e.mode,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel},...e.tier===void 0?{}:{tier:e.tier}}}function ld(e){let{draft:t,catalog:n,fallbackSupported:r,catalogUnavailableReason:i}=e;if(t===void 0)return;if(!sd(t)){if(n===void 0)return{kind:`blocked`,reason:i};let e=Fu(t,n);return e.kind===`blocked`?{kind:`blocked`,reason:e.reason}:{kind:`blocked`,reason:`Choose a provider, model, and thinking level before starting`}}let a=cd(t);if(n===void 0)return r?{kind:`fallback`,requested:a}:{kind:`blocked`,reason:i};let o=Fu(t,n);return o.kind===`ready`?{kind:`ready`}:r?{kind:`fallback`,requested:a,warning:`${o.reason}. ${od}`}:{kind:`blocked`,reason:o.reason}}var ud={economy:`Economy`,fast:`Fast`,standard:`Standard`,advanced:`Advanced`,capable:`Capable`,frontier:`Frontier`},dd=In;function fd(e){return`${e.provider}/${e.id}`}function pd(e){let t=e.thinkingLevel.trim()===``?`no thinking level`:e.thinkingLevel;return`${fd(e.model)} · ${t}`}var md={off:`No reasoning`,minimal:`Very brief reasoning (~1k tokens)`,low:`Light reasoning (~2k tokens)`,medium:`Moderate reasoning (~8k tokens)`,high:`Deep reasoning (~16k tokens)`,xhigh:`Maximum reasoning (~32k tokens)`};function hd(e){let t=new Set(e.supported),n=new Set,r=[];for(let t of[...e.supported,...e.all])n.has(t)||(n.add(t),r.push(t));let i=e=>{let t=dd.findIndex(t=>t===e);return t===-1?dd.length:t};return r.map((e,t)=>({level:e,index:t})).sort((e,t)=>{let n=i(e.level)-i(t.level);return n===0?e.index-t.index:n}).map(({level:n})=>({level:n,supported:t.has(n),selected:n===e.selected,...md[n]===void 0?{}:{description:md[n]}}))}function gd(){return{sessions:[],projectSessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingSessions:!1,selectedNotificationInbox:void 0,treeDialog:void 0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,selectedFileTopLine:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,memory:{kind:`loading`},learnedSkills:{kind:`loading`},selectedTerminalId:void 0,error:``}}function _d(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],projectSessions:[],messages:[],sessionExtensionEntries:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,isLoadingSessions:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],modelPolicy:void 0,isLoadingModelPolicy:!1,isSavingModelPolicy:!1,modelPolicyError:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:`core:workspace.files`,mainView:`chat`,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,memory:{kind:`loading`},learnedSkills:{kind:`loading`},activeTerminalCount:0,selectedTerminalId:void 0,piWebUiStatus:void 0,error:``}}function vd(e,t){return t?.phase===`active`||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function yd(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function bd(e,t){return`${e}:${t}`}function xd(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var Sd=class{constructor(){this.pendingByKey=new Map}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.started&&(n.trailing=!0),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,started:!1,trailing:!1};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1;let n=r.latestRefresh;r.started=!0,t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}},Cd=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Sd,this.api=n.api??Tc,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,wd(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=n.machineActivities[t]??(r?n.workspaceActivities:{});if(!Ed(i,e))return;let a=Td(i,e);this.setState({machineActivities:{...n.machineActivities,[t]:a},...r?{workspaceActivities:a}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...R(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function wd(e){let t={};for(let n of e.workspaces)yd(n)&&(t[n.cwd]=n);return t}function Td(e,t){let n={...e};return yd(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}function Ed(e,t){let n=e[t.cwd];return n===void 0?yd(t):n.hasSessionActivity!==t.hasSessionActivity||n.hasTerminalActivity!==t.hasTerminalActivity}var Dd=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??Lc,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=kd(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){if(e!==void 0&&e!==``){await this.openLoginProvider(e);return}this.setState({authDialog:{step:`method`}})}async chooseLoginMethod(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,authType:e,machineId:R(this.getState())});this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:t}})}catch(e){this.setState({error:String(e)})}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:`API key is required`}});return}let n={...e};delete n.error,this.setState({authDialog:{...n,saving:!0}});try{await this.api.saveApiKey(e.provider.id,t,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(t){this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){try{let{providers:t}=await this.api.authProviders({mode:`logout`,machineId:R(this.getState())});if(e!==void 0&&e!==``){let n=t.find(t=>t.id===e);n!==void 0&&!this.rejectRemoteOAuth(`logout`,n)?await this.logoutProvider(n.id):n===void 0&&this.setState({error:`No stored credentials for ${e}`});return}this.setState({authDialog:{step:`logout`,providers:t}})}catch(e){this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog,n=t?.step===`logout`?t.providers.find(t=>t.id===e):void 0;if(!(n!==void 0&&this.rejectRemoteOAuth(`logout`,n)))try{await this.api.logoutProvider(e,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(e){this.setState({error:String(e)})}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId,o=e??t.inputValue??``,s={...t};delete s.error,this.setState({authDialog:{...s,responding:!0}});try{let e=await this.api.respondOAuthFlow(i,a,o,t.machineId),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||Od(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Od(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.machineId;this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}closeDialog(){this.oauthOperationGeneration+=1,this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,machineId:R(this.getState())}),n=t.filter(t=>t.id===e);if(n.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(n.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:n}});return}let r=n[0];if(r===void 0)return;r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}})}catch(e){this.setState({error:String(e)})}}async startLoginFlow(e){if(this.rejectRemoteOAuth(`login`,e))return;let t=++this.oauthOperationGeneration;this.stopPolling();try{let n=R(this.getState()),r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,n):await this.api.startInteractiveApiKeyLogin(e.id,n);if(t!==this.oauthOperationGeneration){if(r.status===`running`)try{await this.api.cancelOAuthFlow(r.flowId,n)}catch{}return}this.updateOAuthFlow(r,n),r.status===`running`&&this.startPolling(r.flowId,n)}catch(e){t===this.oauthOperationGeneration&&this.setState({error:String(e)})}}rejectRemoteOAuth(e,t){let n=this.getState().selectedMachine;if(t.authType!==`oauth`||n?.kind!==`remote`)return!1;let r=n.baseUrl??`that remote PI WEBUI instance`;return this.setState({error:`OAuth ${e} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&(this.oauthOperationGeneration+=1,this.stopPolling());let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?Od(n.flow):void 0,a=Od(e),o=i!==void 0&&i===a,s=o?r:``,c=o&&n?.step===`oauth`?n.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,machineId:t,inputValue:s,responding:c}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i?.machineId!==t){this.stopPolling();return}let a=Od(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||Od(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||Od(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e=R(this.getState())){let t=this.selectedSessionForMachine(e);if(t!==void 0)try{let n=await this.api.status(t,e),r=this.selectedSessionForMachine(e);if(r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(R(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function Od(e){return e.prompt?.requestId??e.select?.requestId}function kd(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 Ad(e){return e.replaceAll(`:`,`.`)}function jd(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 Md(e,t){let n=jd(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function Nd(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));Pd(i,r)}function Pd(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 Fd(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:nu(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:Vd(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:Vd(0,n),status:`uploading`,startedAt:e.startedAt}}function Id(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 Ld(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=Bd(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function Rd(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,...Bd(r),status:`error`,error:t,completedAt:n}}function zd(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,...Bd(r),status:`cancelled`,error:n,completedAt:t}}function Bd(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Vd(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Hd(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Ud=class{constructor(e,t,n=Hd()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Gd(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function Wd(e){return typeof e==`string`&&e!==``?e:void 0}function Gd(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Kd(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function Kd(e){return!qd(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function qd(e){return typeof e==`object`&&!!e}function Jd(e){let t=e.selectedProject,n=e.selectedWorkspace;return t===void 0||n===void 0?void 0:JSON.stringify([R(e),t.id,n.id])}var Yd=class{constructor(e){this.pending=new Map,this.flush=()=>{this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0,typeof window<`u`&&window.removeEventListener(`pagehide`,this.flush);for(let[e,t]of this.pending)this.positions.set(e,t);this.pending.clear()},this.positions=new Ud(`pi-webui:files-navigation:v1`,Zd,e)}latest(e){let t=this.pending.get(e)??this.positions.get(e);return t===void 0?void 0:{...t}}remember(e,t,n){let r=Zd({path:t,topLine:n});if(r===void 0)return;let i=this.latest(e);i?.path===r.path&&i.topLine===r.topLine||(this.pending.delete(e),this.positions.set(e,r))}rememberLine(e,t,n){let r=this.latest(e);r?.path!==t||!Xd(n)||r.topLine===n||(this.pending.set(e,{path:t,topLine:n}),this.timer===void 0&&(this.timer=setTimeout(this.flush,100),typeof window<`u`&&window.addEventListener(`pagehide`,this.flush)))}forgetScope(e,t){let n=`${JSON.stringify(t===void 0?[e]:[e,t]).slice(0,-1)},`;for(let e of new Set([...this.positions.entries().map(([e])=>e),...this.pending.keys()]))e.startsWith(n)&&this.forget(e)}forget(e){this.pending.delete(e),this.positions.delete(e)}};function Xd(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function Zd(e){if(typeof e!=`object`||!e||!(`path`in e)||typeof e.path!=`string`)return;let t=e.path;if(t===``||t.startsWith(`/`)||t.includes(`\\`)||t.split(`/`).some(e=>e===`..`||e===`.`||e===``))return;let n=`topLine`in e&&Xd(e.topLine)?e.topLine:void 0;return n===void 0?{path:t}:{path:t,topLine:n}}var Qd=Ad(`core:workspace.files`),$d=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.workspaceGeneration=0,this.fileRequest=0,this.refreshRequest=0,this.treeGeneration=0,this.collapseGeneration=0,this.directoryRequests=new Map,this.api=r.api??Lc,this.memory=r.memory??new Yd,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??iu,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}workspaceChanged(){this.workspaceGeneration+=1,this.fileRequest+=1,this.treeGeneration+=1,this.collapseGeneration+=1,this.directoryRequests.clear()}forgetScope(e,t){this.memory.forgetScope(e,t)}topLine(e){let t=Jd(this.getState()),n=t===void 0?void 0:this.memory.latest(t);return n?.path===e?n?.topLine:void 0}rememberTopLine(e,t,n){this.memory.rememberLine(e,t,n)}async restoreRememberedFile(e){let t=this.captureScope();if(t===void 0)return;let n=e??this.memory.latest(t.key)?.path,r=++this.fileRequest,i=this.treeGeneration;await this.refreshFiles(),!(!t.current()||r!==this.fileRequest||n===void 0)&&(await this.restoreFile(n,i),!(!t.current()||this.getState().selectedFilePath!==n)&&(Nd(Qd,`file`,this.getState().selectedFilePath),this.updateUrl({replace:!0})))}collapseAll(){this.treeGeneration+=1,this.collapseGeneration+=1,this.setState({expandedDirs:{}})}async refreshFiles(){let e=this.captureScope();if(e===void 0)return;let t=++this.refreshRequest,n=this.treeGeneration,r={...this.getState().expandedDirs};try{let i=await this.api.workspaceTree(e.projectId,e.workspaceId,``,e.machineId);if(await Promise.all(Object.keys(r).map(async t=>{try{r[t]=(await this.api.workspaceTree(e.projectId,e.workspaceId,t,e.machineId)).entries}catch(e){if(!ef(e))throw e;r=rf(r,t)}})),!e.current()||t!==this.refreshRequest)return;this.setState({fileTree:i.entries,...n===this.treeGeneration?{expandedDirs:r}:{},fileTreeStale:!1,error:``})}catch(n){e.current()&&t===this.refreshRequest&&this.setState({error:String(n)})}}async expandDir(e){let t=this.captureScope();if(t===void 0)return;let n=(this.directoryRequests.get(e)??0)+1;this.directoryRequests.set(e,n),this.treeGeneration+=1;let r=this.collapseGeneration;if(this.getState().expandedDirs[e]!==void 0){let t=`${e}/`;for(let[e,n]of this.directoryRequests)e.startsWith(t)&&this.directoryRequests.set(e,n+1);this.setState({expandedDirs:Object.fromEntries(Object.entries(this.getState().expandedDirs).filter(([n])=>n!==e&&!n.startsWith(t)))});return}try{let i=await this.api.workspaceTree(t.projectId,t.workspaceId,e,t.machineId);if(!t.current()||r!==this.collapseGeneration||n!==this.directoryRequests.get(e))return;this.treeGeneration+=1,this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:i.entries},error:``})}catch(i){t.current()&&r===this.collapseGeneration&&n===this.directoryRequests.get(e)&&this.setState({error:String(i)})}}captureScope(){let e=this.getState(),t=Jd(e);if(t===void 0||e.selectedProject===void 0||e.selectedWorkspace===void 0)return;let n=this.workspaceGeneration;return{key:t,projectId:e.selectedProject.id,workspaceId:e.selectedWorkspace.id,machineId:R(e),current:()=>n===this.workspaceGeneration&&t===Jd(this.getState())}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),Nd(Qd,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e,t=this.treeGeneration){let n=this.captureScope();if(n===void 0)return;let r=++this.fileRequest,i=t,a=()=>n.current()&&r===this.fileRequest,o=this.memory.latest(n.key),s=o?.path===e?o.topLine??1:1;this.setState({selectedFilePath:e,selectedFileContent:void 0,selectedFileTopLine:s});try{let t=await this.api.workspaceFile(n.projectId,n.workspaceId,e,n.machineId);if(!a())return;let r=this.memory.latest(n.key),i=r?.path===e?r.topLine??1:1;this.memory.remember(n.key,e,t.mediaType===`image`||t.binary?void 0:i),this.setState({selectedFileContent:t,selectedFileTopLine:i,error:``})}catch(t){if(!a())return;if(ef(t)){this.memory.latest(n.key)?.path===e&&this.memory.forget(n.key),this.setState({selectedFilePath:void 0,selectedFileContent:void 0,selectedFileTopLine:void 0,error:``}),Nd(Qd,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)});return}if(!a()||i!==this.treeGeneration)return;let c=e.split(`/`).slice(0,-1).map((e,t,n)=>n.slice(0,t+1).join(`/`));try{let e=await Promise.all(c.map(async e=>[e,(await this.api.workspaceTree(n.projectId,n.workspaceId,e,n.machineId)).entries]));a()&&i===this.treeGeneration&&(this.treeGeneration+=1,this.setState({expandedDirs:{...this.getState().expandedDirs,...Object.fromEntries(e)}}))}catch(e){if(!a()||i!==this.treeGeneration)return;ef(e)?(this.memory.forget(n.key),this.setState({selectedFilePath:void 0,selectedFileContent:void 0,selectedFileTopLine:void 0}),Nd(Qd,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0})):this.setState({error:String(e)})}}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`Select a workspace before uploading files.`});return}if(e.length===0)return;let i=R(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=Fd({id:this.createUploadBatchId(),projectId:n.id,workspaceId:r.id,machineId:i,destinationFolder:t.destinationFolder,overwrite:a,createDirs:o,files:e,startedAt:this.now()})}catch(e){this.setState({error:String(e)});return}this.setUploadBatch(s);let c;try{c=this.uploadWorkspaceFiles(n.id,r.id,e,{destinationFolder:t.destinationFolder,machineId:i,overwrite:a,createDirs:o,onProgress:e=>{this.updateUploadProgress(s.id,e)}})}catch(e){return this.failUploadBatch(s.id,e),{batchId:s.id,done:Promise.resolve()}}this.uploadTasks.set(s.id,c);let l=c.promise.then(async e=>{await this.completeUploadBatch(s.id,e,t)}).catch(async e=>{await this.handleUploadFailure(s.id,e,t)}).finally(()=>{this.uploadTasks.delete(s.id)});return{batchId:s.id,done:l}}cancelWorkspaceUpload(e){let t=this.getUploadBatch(e);t?.status===`uploading`&&(this.setUploadBatch(zd(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:rf(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(Id(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(Ld(r,t,this.now()),{error:``}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();let i=t[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}async handleUploadFailure(e,t,n){let r=this.failUploadBatch(e,t);if(!(t instanceof $l)||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(tf(t)){let e=zd(n,this.now());return this.setUploadBatch(e),e}let r=nf(t),i=Rd(n,r,this.now());return this.setUploadBatch(i,{error:r}),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e,t={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e},...t})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&R(t)===e.machineId}};function ef(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function tf(e){return e instanceof Ql}function nf(e){return e instanceof Error?e.message:String(e)}function rf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var af=Ad(`core:workspace.git`),of=class{constructor(e,t,n){this.getState=e,this.setState=t,this.updateUrl=n,this.statusRequest=0,this.diffRequest=0}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0,this.pollingScope=void 0,this.statusRequest+=1,this.diffRequest+=1}async refreshGit(e={}){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(this.getState()),i=++this.statusRequest;this.diffRequest+=1;try{let a=await Lc.gitStatus(t.id,n.id,r);if(i!==this.statusRequest||!this.isCurrentWorkspace(t,n,r))return;this.setState({gitStatus:a,gitStale:!1,...e.reportError===!1?{}:{error:``}});let o=this.getState().selectedDiffPath;o!==void 0&&(a.files.some(e=>e.path===o)?await this.refreshDiff(o,e):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Nd(af,`diff`,void 0,{replace:!0})))}catch(a){if(i!==this.statusRequest||!this.isCurrentWorkspace(t,n,r))return;e.reportError!==!1&&this.setState({error:String(a)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:`core:workspace.git`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.git`}),Nd(af,`diff`,e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e,t={}){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0)return;let i=R(this.getState()),a=++this.diffRequest;try{let[o,s]=await Promise.all([Lc.gitDiff(n.id,r.id,{path:e},i),Lc.gitDiff(n.id,r.id,{path:e,staged:!0},i)]);if(a!==this.diffRequest||!this.isCurrentWorkspace(n,r,i))return;this.setState({selectedDiff:o,selectedStagedDiff:s,...t.reportError===!1?{}:{error:``}})}catch(e){if(a!==this.diffRequest||!this.isCurrentWorkspace(n,r,i))return;t.reportError!==!1&&this.setState({error:String(e)})}}updatePolling(){let e=this.currentPollingScope();e===this.pollingScope&&this.pollTimer!==void 0||(this.dispose(),e!==void 0&&(this.pollingScope=e,this.refreshGit({reportError:!1}),this.pollTimer=window.setInterval(()=>{this.refreshGit({reportError:!1})},8e3)))}currentPollingScope(){let e=this.getState();if(!(e.selectedProject===void 0||e.selectedWorkspace?.isGitRepo!==!0))return JSON.stringify([R(e),e.selectedProject.id,e.selectedWorkspace.id])}isCurrentWorkspace(e,t,n){let r=this.getState();return R(r)===n&&r.selectedProject?.id===e.id&&r.selectedWorkspace?.id===t.id&&r.selectedWorkspace.projectId===t.projectId}},sf=3e4,cf={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},lf=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??ic.snapshot,this.timer=n.timer??cf,this.pollIntervalMs=n.pollIntervalMs??sf}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}if(this.scope?.key!==t.key){this.startScope(t);return}this.inFlight?.generation===this.generation&&this.inFlight.scopeKey===t.key||this.pollTimer===void 0&&this.startRequest(t)}async refresh(){if(!this.observing)return;let e=this.currentScope();if(e===void 0){this.invalidateScope();return}if(this.scope?.key!==e.key){await this.startScope(e);return}this.clearPollTimer(),await this.startRequest(e)}dispose(){this.observing=!1,this.invalidateScope()}startScope(e){return this.invalidateScope(),this.scope=e,this.setState({learnedSkills:{kind:`loading`}}),this.startRequest(e)}startRequest(e){let t=this.inFlight;if(t?.generation===this.generation&&t.scopeKey===e.key)return t.promise;let n=this.generation,r=++this.nextRequestId,i={generation:n,requestId:r,scopeKey:e.key,promise:Promise.resolve()};this.inFlight=i;let a=this.load(e,n,r);return i.promise=a,a}async load(e,t,n){try{let n=await this.fetchSnapshot(e.workspacePath,e.machineId);if(!this.isCurrent(e,t))return;let r=uf(n);this.setState({learnedSkills:r}),r.kind===`unavailable`&&this.stopObserving()}catch(n){if(!this.isCurrent(e,t))return;this.applyFailure(String(n))}finally{let r=this.inFlight?.requestId===n;r&&(this.inFlight=void 0),r&&this.isCurrent(e,t)&&this.scheduleNext(e,t)}}applyFailure(e){let t=this.getState().learnedSkills;if(t.kind===`data`){this.setState({learnedSkills:{...t,refreshError:e}});return}this.setState({learnedSkills:{kind:`error`,message:e}})}scheduleNext(e,t){this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.observing||!this.isCurrent(e,t))&&this.startRequest(e)},this.pollIntervalMs)}stopObserving(){this.observing&&(this.observing=!1,this.invalidateScope())}invalidateScope(){this.clearPollTimer(),this.scope=void 0,this.inFlight=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}currentScope(){let e=this.getState(),t=e.selectedProject,n=e.selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(e);return{key:JSON.stringify([r,t.id,n.id,n.path]),machineId:r,projectId:t.id,workspaceId:n.id,workspacePath:n.path}}isCurrent(e,t){if(!this.observing||t!==this.generation||this.scope?.key!==e.key)return!1;let n=this.currentScope();return n?.machineId===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.workspacePath===e.workspacePath}};function uf(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalSkills:e.globalSkills,projectSkills:e.projectSkills,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}var df=3e4,ff={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},pf=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??nc.snapshot,this.timer=n.timer??ff,this.pollIntervalMs=n.pollIntervalMs??df}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}if(this.scope?.key!==t.key){this.startScope(t);return}this.inFlight?.generation===this.generation&&this.inFlight.scopeKey===t.key||this.pollTimer===void 0&&this.startRequest(t)}async refresh(){if(!this.observing)return;let e=this.currentScope();if(e===void 0){this.invalidateScope();return}if(this.scope?.key!==e.key){await this.startScope(e);return}this.clearPollTimer(),await this.startRequest(e)}dispose(){this.observing=!1,this.invalidateScope()}startScope(e){return this.invalidateScope(),this.scope=e,this.setState({memory:{kind:`loading`}}),this.startRequest(e)}startRequest(e){let t=this.inFlight;if(t?.generation===this.generation&&t.scopeKey===e.key)return t.promise;let n=this.generation,r=++this.nextRequestId,i={generation:n,requestId:r,scopeKey:e.key,promise:Promise.resolve()};this.inFlight=i;let a=this.load(e,n,r);return i.promise=a,a}async load(e,t,n){try{let n=await this.fetchSnapshot(e.workspacePath,e.machineId);if(!this.isCurrent(e,t))return;let r=mf(n);this.setState({memory:r}),r.kind===`unavailable`&&this.stopObserving()}catch(n){if(!this.isCurrent(e,t))return;this.applyFailure(String(n))}finally{let r=this.inFlight?.requestId===n;r&&(this.inFlight=void 0),r&&this.isCurrent(e,t)&&this.scheduleNext(e,t)}}applyFailure(e){let t=this.getState().memory;if(t.kind===`data`){this.setState({memory:{...t,refreshError:e}});return}this.setState({memory:{kind:`error`,message:e}})}scheduleNext(e,t){this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.observing||!this.isCurrent(e,t))&&this.startRequest(e)},this.pollIntervalMs)}stopObserving(){this.observing&&(this.observing=!1,this.invalidateScope())}invalidateScope(){this.clearPollTimer(),this.scope=void 0,this.inFlight=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}currentScope(){let e=this.getState(),t=e.selectedProject,n=e.selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(e);return{key:JSON.stringify([r,t.id,n.id,n.path]),machineId:r,projectId:t.id,workspaceId:n.id,workspacePath:n.path}}isCurrent(e,t){if(!this.observing||t!==this.generation||this.scope?.key!==e.key)return!1;let n=this.currentScope();return n?.machineId===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.workspacePath===e.workspacePath}};function mf(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalEntries:e.globalEntries,projectEntries:e.projectEntries,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}function hf(e){let t=[],n=[];for(let r of e)xf(r.index)&&t.push(bf(r,`staged`,r.index)),Sf(r.workingTree)&&n.push(bf(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function gf(e){let t=hf(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function _f(e){switch(e){case`modified`:return`M`;case`added`:return`A`;case`deleted`:return`D`;case`renamed`:return`R`;case`copied`:return`C`;case`untracked`:return`?`;case`conflicted`:return`U`;case`ignored`:return`!`;case`unmodified`:return``}}function vf(e){switch(e){case`modified`:return`Modified`;case`added`:return`Added`;case`deleted`:return`Deleted`;case`renamed`:return`Renamed`;case`copied`:return`Copied`;case`untracked`:return`Untracked`;case`conflicted`:return`Conflicted`;case`ignored`:return`Ignored`;case`unmodified`:return`Unmodified`}}function yf(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function bf(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function xf(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function Sf(e){return e!==`unmodified`&&e!==`ignored`}var Cf=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 Lc.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:Tf(this.getState().machineActivities,r),machineRuntimes:Tf(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t)}catch(e){this.setState({error:String(e)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...gd()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){this.setState({error:``});try{let t=await Lc.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 Lc.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:wf(this.getState().machineStatuses,e.id),machineRuntimes:wf(this.getState().machineRuntimes,e.id),machineActivities:wf(this.getState().machineActivities,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(e){this.setState({error:String(e)});return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await Lc.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 Lc.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 Lc.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=>Lc.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=>Lc.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 wf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Tf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Ef=`~/workspace`,Df=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.projectCatalogOperationSequence=0,this.pinMutationQueueByMachine=new Map,this.latestPinMutationOrderByMachine=new Map,this.api=r.api??Lc,this.onProjectsApplied=r.onProjectsApplied}async loadProjects(){let e=R(this.getState()),t=++this.projectCatalogOperationSequence;this.setState({error:``,isLoadingProjects:!0});try{let n=await this.api.projects(e);if(!this.isCurrentProjectCatalogOperation(e,t))return!1;let r;if(n.length===0){if(r=await this.api.addProject(Ef,void 0,!0,e),!this.isCurrentProjectCatalogOperation(e,t))return!1;n=[r]}let i=new Set(n.map(e=>e.id)),a=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>i.has(e))),o=this.getState().selectedProject,s=o!==void 0&&n.some(e=>e.id===o.id&&e.path!==o.path);return this.setState({projects:n,workspacesByProjectId:a}),s&&this.workspaces.clearSelection(),this.onProjectsApplied?.(e),r!==void 0&&await this.workspaces.selectProject(r),!0}catch(n){return this.isCurrentProjectCatalogOperation(e,t)&&this.setState({error:String(n)}),!1}finally{this.isCurrentProjectCatalogOperation(e,t)&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=R(this.getState()),r=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});try{let i=await this.api.addProject(e.trim(),void 0,t,n);if(R(this.getState())!==n)return;if(!this.isCurrentProjectCatalogOperation(n,r)){this.setState({projectDialogOpen:!1}),await this.loadProjects();return}let a=this.getState().projects;this.setState({projects:[...a.filter(e=>e.id!==i.id),i],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(i)}catch(e){this.isCurrentProjectCatalogOperation(n,r)&&this.setState({error:String(e)})}}async addRegisteredProject(e,t){if(e.trim()===``)throw Error(`Project path is required`);let n=R(this.getState()),r=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});try{let i=await this.api.addProject(e,t,!1,n);if(R(this.getState())!==n)return i;if(!this.isCurrentProjectCatalogOperation(n,r))return await this.loadProjects(),i;let a=this.getState().projects;return this.setState({projects:[...a.filter(e=>e.id!==i.id),i]}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(i),i}catch(e){throw e instanceof Error?e:Error(String(e))}}async closeProject(e){let t=R(this.getState());try{if(await this.api.closeProject(e,t),R(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){R(this.getState())===t&&this.setState({error:String(e)})}}async closeProjectTree(e){let t=R(this.getState()),n=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});try{let{closedProjectIds:r}=await this.api.closeProjectTree(e,t);if(R(this.getState())!==t)return;for(let e of r)this.workspaces.forgetProject(e);let i=this.getState(),a=new Set(r);this.setState({projects:i.projects.filter(e=>!a.has(e.id))}),this.onProjectsApplied?.(t),i.selectedProject!==void 0&&a.has(i.selectedProject.id)&&this.workspaces.clearSelection(),this.isCurrentProjectCatalogOperation(t,n)||await this.loadProjects()}catch(e){this.isCurrentProjectCatalogOperation(t,n)&&this.setState({error:String(e)})}}async pinProject(e){await this.applyPinChange(e,t=>this.api.pinProject(e,t))}async unpinProject(e){await this.applyPinChange(e,t=>this.api.unpinProject(e,t))}async applyPinChange(e,t){let n=R(this.getState()),r=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});let i=(this.latestPinMutationOrderByMachine.get(n)??0)+1;this.latestPinMutationOrderByMachine.set(n,i);let a=this.pinMutationQueueByMachine.get(n),o=a===void 0?this.runPinChange(n,r,i,t):a.catch(()=>void 0).then(async()=>{await this.runPinChange(n,r,i,t)});this.pinMutationQueueByMachine.set(n,o);try{await o}finally{this.cleanupPinMutationQueue(n,i,o)}}async runPinChange(e,t,n,r){try{let i=await r(e);if(!this.isLatestPinMutation(e,n))return;this.isCurrentProjectCatalogOperation(e,t)?this.setState({projects:i}):R(this.getState())===e&&await this.loadProjects()}catch(r){this.isCurrentPinMutation(e,t,n)&&this.setState({error:String(r)})}}isCurrentProjectCatalogOperation(e,t){return R(this.getState())===e&&this.projectCatalogOperationSequence===t}isLatestPinMutation(e,t){return this.latestPinMutationOrderByMachine.get(e)===t}isCurrentPinMutation(e,t,n){return this.isCurrentProjectCatalogOperation(e,t)&&this.isLatestPinMutation(e,n)}cleanupPinMutationQueue(e,t,n){this.pinMutationQueueByMachine.get(e)===n&&(this.pinMutationQueueByMachine.delete(e),this.latestPinMutationOrderByMachine.get(e)===t&&this.latestPinMutationOrderByMachine.delete(e))}},Of=5e3,kf=`reconcile selected project catalog`,Af={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},jf=class{constructor(e,t){this.getState=e,this.generation=0,this.nextRequestId=0,this.observing=!1,this.listWorkspaces=t.workspaces??Oc.workspaces,this.applySnapshot=t.applySnapshot,this.timer=t.timer??Af,this.pollIntervalMs=t.pollIntervalMs??Of,this.onBackgroundError=t.onBackgroundError,this.captureTopologyRequest=t.captureTopologyRequest}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}let n=this.retargetScope(t);this.inFlight===void 0&&(!n&&this.pollTimer!==void 0||this.scheduleNext(t,this.generation))}refresh(){if(!this.observing)return Promise.resolve();let e=this.currentScope();if(e===void 0)return this.invalidateScope(),Promise.resolve();this.retargetScope(e),this.clearPollTimer();let t=this.generation,n=this.inFlight;return n===void 0?this.startRequest(e,t):n.generation===t&&n.scopeKey===e.key?n.promise:this.queueImmediateRefresh(e,t)}dispose(){this.observing=!1,this.invalidateScope()}retargetScope(e){return this.scope?.key===e.key?(this.scope=e,!1):(this.clearPollTimer(),this.clearQueuedImmediateRefresh(),this.scope=e,this.generation+=1,!0)}startRequest(e,t){let n=this.inFlight;if(n!==void 0)return n.generation===t&&n.scopeKey===e.key?n.promise:this.queueImmediateRefresh(e,t);let r=++this.nextRequestId,i,a=new Promise(e=>{i=e});if(i===void 0)throw Error(`Project catalog request promise was not initialized`);return this.inFlight={generation:t,requestId:r,scopeKey:e.key,promise:a},this.load(e,t,r).then(i,i),a}async load(e,t,n){try{let n=this.captureTopologyRequest?.({machineId:e.machineId,projectId:e.project.id,projectPath:e.project.path}),r=await this.listWorkspaces(e.project.id,e.machineId);if(!this.isCurrent(e,t))return;await this.applySnapshot({machineId:e.machineId,project:e.project,workspaces:r,...n===void 0?{}:{topologyRequest:n}})}catch(n){this.isCurrent(e,t)&&this.reportBackgroundError(n)}finally{this.finishRequest(n)}}finishRequest(e){if(this.inFlight?.requestId!==e)return;this.inFlight=void 0;let t=this.queuedImmediateRefresh;if(t!==void 0){if(this.queuedImmediateRefresh=void 0,this.isCurrent(t.scope,t.generation)){this.startRequest(t.scope,t.generation).then(()=>{t.resolve()},()=>{t.resolve()});return}t.resolve()}let n=this.scope;n!==void 0&&this.isCurrent(n,this.generation)&&this.scheduleNext(n,this.generation)}queueImmediateRefresh(e,t){let n=this.queuedImmediateRefresh;if(n?.generation===t&&n.scope.key===e.key)return n.promise;this.clearQueuedImmediateRefresh();let r,i=new Promise(e=>{r=e});if(r===void 0)throw Error(`Queued project catalog refresh promise was not initialized`);return this.queuedImmediateRefresh={generation:t,scope:e,promise:i,resolve:r},i}scheduleNext(e,t){this.isCurrent(e,t)&&(this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.isCurrent(e,t)||this.inFlight!==void 0)&&this.startRequest(e,t)},this.pollIntervalMs))}stopObserving(){this.observing=!1,this.invalidateScope()}invalidateScope(){this.clearPollTimer(),this.clearQueuedImmediateRefresh(),this.scope=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}clearQueuedImmediateRefresh(){let e=this.queuedImmediateRefresh;this.queuedImmediateRefresh=void 0,e?.resolve()}currentScope(){let e=this.getState(),t=e.selectedProject;if(t===void 0||e.isLoadingWorkspaces)return;let n=R(e);return{key:JSON.stringify([n,t.id,t.path]),machineId:n,project:t}}isCurrent(e,t){return!this.observing||t!==this.generation||this.scope?.key!==e.key?!1:this.currentScope()?.key===e.key}reportBackgroundError(e){if(this.onBackgroundError!==void 0)try{this.onBackgroundError(kf,e)}catch{}}},Mf=`record recent project`,Nf=class{constructor(e){this.deps=e,this.current={kind:`loading`},this.queuesByMachine=new Map,this.authoritativeProjectIdByMachine=new Map,this.latestIntentByMachine=new Map,this.generation=0,this.api=e.api??Dc}get state(){return this.current}async load(){let e=this.deps.machineId(),t=++this.generation;this.latestIntentByMachine.delete(e),this.authoritativeProjectIdByMachine.delete(e),this.publish({kind:`loading`}),await this.enqueue(e,async()=>{this.authoritativeProjectIdByMachine.delete(e);try{let n=await this.api.recentProjects(e);if(this.isStale(t,e))return;this.publish({kind:`ready`,entries:n})}catch(n){if(this.isStale(t,e))return;this.publish({kind:`failed`,message:Pf(n)})}})}retry(){return this.load()}recordWork(e,t=this.deps.machineId()){if(this.latestIntentByMachine.get(t)?.projectId===e)return;let n={projectId:e};this.latestIntentByMachine.set(t,n);let r=this.generation;this.enqueue(t,async()=>{if(this.authoritativeProjectIdByMachine.get(t)!==e)try{let n=await this.api.recordRecentProject(e,t);if(this.authoritativeProjectIdByMachine.set(t,e),this.isStale(r,t))return;this.publish({kind:`ready`,entries:n})}catch(e){this.latestIntentByMachine.get(t)===n&&this.latestIntentByMachine.delete(t),this.deps.onBackgroundError?.(Mf,e)}})}async removeEntry(e){let t=this.deps.machineId();this.latestIntentByMachine.delete(t),this.authoritativeProjectIdByMachine.delete(t);let n=this.generation,r;if(await this.enqueue(t,async()=>{try{let r=await this.api.removeRecentProject(e,t);this.authoritativeProjectIdByMachine.delete(t),this.isStale(n,t)||this.publish({kind:`ready`,entries:r})}catch(e){r=e instanceof Error?e:Error(String(e))}}),r!==void 0)throw r;return{kind:`removed`}}enqueue(e,t){let n=(this.queuesByMachine.get(e)??Promise.resolve()).then(t,t),r=n.catch(()=>void 0);return this.queuesByMachine.set(e,r),r.then(()=>{this.queuesByMachine.get(e)===r&&this.queuesByMachine.delete(e)}),n}isStale(e,t){return e!==this.generation||t!==this.deps.machineId()}publish(e){this.current=e,this.deps.onChange(e)}};function Pf(e){return e instanceof Error?e.message:String(e)}function Ff(e,t){return t[e.path]}function If(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Lf(e,t,n){return Bf(Vf(e,t,n))}function Rf(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function zf(e){return Bf(Object.values(e??{}))}function Bf(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Vf(e,t,n){return Object.values(n).filter(n=>Rf(e,t,n.cwd))}var Hf=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??Oc,this.onProjectTopology=n.onProjectTopology,this.captureTopologyRequest=n.captureTopologyRequest,this.onError=n.onError}handleActivityApplied(e){return R(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return R(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(R(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!Uf(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=this.captureTopologyRequest?.({machineId:e.machineId,projectId:t.id,projectPath:t.path}),r=await this.api.workspaces(t.id,e.machineId);await this.applyProjectWorkspaces(e,t,r,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!Uf(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(R(this.getState()))}async applyProjectWorkspaces(e,t,n,r){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let i=this.getState();if(i.projects.find(e=>e.id===t.id)?.path===t.path&&!(r===void 0&&i.workspacesByProjectId[t.id]!==t.startingWorkspaces)){if(this.onProjectTopology!==void 0){await this.onProjectTopology({machineId:e.machineId,projectId:t.id,projectPath:t.path,workspaces:n,...r===void 0?{}:{topologyRequest:r}});return}this.setState({workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:n}})}}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&R(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(yd).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function Uf(e,t,n){return e.some(e=>Rf(e,t[e.id]??[],n))}var Wf=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??Xs,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=R(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebUiStatus(e);this.isCurrent(e,t)&&this.setState({piWebUiStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebUiStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=R(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebUiStatus:t}),Gf(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return R(this.getState())===e&&t===this.requestSequence}};function Gf(e){if(e.release.error!==void 0)throw Error(`PI WEBUI update check failed: ${e.release.error}`);if(e.release.skipped===!0)throw Error(`PI WEBUI update check was skipped because remote version checks are disabled by offline/version-check settings`)}var Kf=`pi-webui:cached-new-sessions:v1`,qf=`browserCachedNew`,Jf=`local`;function Yf(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Xf(e,t=Jf,n=Yf()){if(e.messageCount!==0||e.archived===!0)return;let r=np(n).filter(n=>n.id!==e.id||n.machineId!==t);rp([Zf(e,t),...r],n)}function Zf(e,t=Jf){return{...e,browserCachedNew:!0,machineId:t}}function Qf(e,t=Jf,n=Yf()){rp(np(n).filter(n=>n.id!==e||n.machineId!==t),n)}function $f(e,t,n=Jf,r=Yf()){let i=new Set(t.map(e=>e.id)),a=np(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&rp(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function ep(e){return e!==void 0&&ap(e)&&e.browserCachedNew===!0}function tp(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:Jf},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt},...e.creationSource===void 0?{}:{creationSource:e.creationSource}}}function np(e=Yf()){try{let t=e?.getItem(Kf);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>ip(e)):[]}catch{return[]}}function rp(e,t=Yf()){try{e.length===0?t?.removeItem(Kf):t?.setItem(Kf,JSON.stringify(e))}catch{}}function ip(e){if(!op(e))return[];let t=sp(e,`id`),n=sp(e,`path`),r=sp(e,`cwd`),i=sp(e,`created`),a=sp(e,`modified`),o=sp(e,`firstMessage`),s=lp(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=cp(e,`name`),l=cp(e,`parentSessionPath`),u=cp(e,`machineId`)??Jf,d=e.creationSource===`session-list-plus`?e.creationSource:void 0;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},...d===void 0?{}:{creationSource:d},machineId:u,browserCachedNew:!0}]}function ap(e){return qf in e}function op(e){return typeof e==`object`&&!!e}function sp(e,t){let n=e[t];return typeof n==`string`?n:void 0}function cp(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function lp(e,t){let n=e[t];return typeof n==`number`?n:void 0}function up(e){return kp(e.flatMap(hp)).filter(e=>e.parts.length>0)}function dp(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function fp(e,t){let n=xp(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=Rp(t,`canFork`);return{...e,...n===void 0?{}:{meta:n},...r===void 0?{}:{entryId:r},...i===void 0?{}:{previousAssistantEntryId:i},...a===void 0?{}:{canFork:a}}}function pp(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,dp(t,n)]}function mp(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 hp(e){if(_p(e))return[e];if(z(e,`role`)===`bashExecution`)return[fp(wp(e),e)];let t=Tp(z(e,`role`)),n=Ep(Lp(e,`content`),e),r=t===`user`?vp(n):void 0;if(r!==void 0)return r.map(t=>fp(t,e));let i=bp(e);if(t===`tool`)return[fp({role:t,parts:n,...i===void 0?{}:{source:i}},e)];let a=n.filter(e=>e.type!==`empty`),o=t===`assistant`&&a.length>0&&a.every(e=>e.type===`skillRead`)?`skill`:t,s=a.length>0?[fp({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=gp(e);return c===void 0?s:[...s,fp(c,e)]}function gp(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return dp(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function _p(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Lp(e,`parts`))}function vp(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=yp(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 yp(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 bp(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function xp(e){let t=Sp(Lp(e,`timestamp`)),n=Cp(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function Sp(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 Cp(e){if(z(e,`role`)!==`assistant`)return;let t=z(e,`provider`),n=z(e,`model`),r=z(e,`responseModel`);if(!((t===void 0||t===``)&&(n===void 0||n===``)&&(r===void 0||r===``)))return{...t===void 0||t===``?{}:{provider:t},...n===void 0||n===``?{}:{id:n},...r===void 0||r===``?{}:{responseId:r}}}function wp(e){let t=z(e,`command`)??``,n=Rp(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Lp(e,`output`);r!=null&&n.push(``,Bp(r));let i=Lp(e,`exitCode`);i!=null&&n.push(``,`exit ${Bp(i)}`),Rp(e,`cancelled`)===!0&&n.push(``,`cancelled`),Rp(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=z(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
@@ -1223,7 +1223,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1223
1223
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1224
1224
|
.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; }
|
|
1225
1225
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1226
|
-
`]}};H([x({attribute:!1})],PS.prototype,`context`,void 0),H([C(`#workspace-upload-input`)],PS.prototype,`uploadInput`,void 0),H([S()],PS.prototype,`pendingUpload`,void 0),H([S()],PS.prototype,`destinationFolder`,void 0),H([S()],PS.prototype,`overwrite`,void 0),H([S()],PS.prototype,`createDirs`,void 0),H([S()],PS.prototype,`formError`,void 0),H([S()],PS.prototype,`dragActive`,void 0),PS=H([b(`workspace-files-panel`)],PS);function FS(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 IS(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{nu(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function LS(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function RS(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${ZS(t.size)}`}function zS(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function BS(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function VS(e){return e==null?[]:Array.from(e)}function HS(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function US(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function WS(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 GS(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return YS(e.percent)}}function KS(e){return e.status===`uploading`?e.percent:1}function qS(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return YS(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function JS(e){return e.error===void 0?e.response===void 0?`${e.path} · ${ZS(e.loaded)} / ${ZS(e.total)}`:`Wrote ${e.response.path}`:e.error}function YS(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function XS(){NS(()=>import(`./CodeViewer-
|
|
1226
|
+
`]}};H([x({attribute:!1})],PS.prototype,`context`,void 0),H([C(`#workspace-upload-input`)],PS.prototype,`uploadInput`,void 0),H([S()],PS.prototype,`pendingUpload`,void 0),H([S()],PS.prototype,`destinationFolder`,void 0),H([S()],PS.prototype,`overwrite`,void 0),H([S()],PS.prototype,`createDirs`,void 0),H([S()],PS.prototype,`formError`,void 0),H([S()],PS.prototype,`dragActive`,void 0),PS=H([b(`workspace-files-panel`)],PS);function FS(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 IS(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{nu(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function LS(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function RS(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${ZS(t.size)}`}function zS(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function BS(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function VS(e){return e==null?[]:Array.from(e)}function HS(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function US(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function WS(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 GS(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return YS(e.percent)}}function KS(e){return e.status===`uploading`?e.percent:1}function qS(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return YS(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function JS(e){return e.error===void 0?e.response===void 0?`${e.path} · ${ZS(e.loaded)} / ${ZS(e.total)}`:`Wrote ${e.response.path}`:e.error}function YS(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function XS(){NS(()=>import(`./CodeViewer-DAKOouFS.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function ZS(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${QS(t)} KB`;let n=t/1024;return n<1024?`${QS(n)} MB`:`${QS(n/1024)} GB`}function QS(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var $S=2e3,eC=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.dynamicMetricsRequest=0,this.dynamicMetricsRefreshInFlight=!1}willUpdate(e){if(!e.has(`context`))return;let t=this.context?.machine.id;if(t===void 0){this.stopDynamicMetricsPolling(),this.machineId=void 0;return}t!==this.machineId&&(this.stopDynamicMetricsPolling(),this.machineId=t,this.loadSystemInfo(t))}async loadSystemInfo(e=this.machineId){if(e!==void 0){this.loading=!0,this.error=``;try{let t=await Xs.systemInfo(e);this.isCurrentMachine(e)&&(this.systemInfo=t,this.isConnected&&this.startDynamicMetricsPolling())}catch(t){this.isCurrentMachine(e)&&(this.error=t instanceof Error?t.message:String(t))}finally{this.isCurrentMachine(e)&&(this.loading=!1)}}}connectedCallback(){super.connectedCallback(),this.startDynamicMetricsPolling()}disconnectedCallback(){this.stopDynamicMetricsPolling(),super.disconnectedCallback()}startDynamicMetricsPolling(){let e=this.machineId;e===void 0||this.systemInfo===void 0||this.dynamicMetricsTimer!==void 0||(this.dynamicMetricsPollingMachineId=e,this.dynamicMetricsTimer=window.setInterval(()=>{this.refreshDynamicMetrics(e)},$S))}stopDynamicMetricsPolling(){this.dynamicMetricsTimer!==void 0&&window.clearInterval(this.dynamicMetricsTimer),this.dynamicMetricsTimer=void 0,this.dynamicMetricsPollingMachineId=void 0,this.dynamicMetricsRequest+=1,this.dynamicMetricsRefreshInFlight=!1}async refreshDynamicMetrics(e){if(this.loading||this.error!==``||this.dynamicMetricsRefreshInFlight||this.dynamicMetricsPollingMachineId!==e)return;this.dynamicMetricsRefreshInFlight=!0;let t=++this.dynamicMetricsRequest;try{let n=await Xs.systemMetrics(e);if(!this.isCurrentDynamicMetricsRequest(e,t))return;this.applyDynamicMetrics(n)}catch{}finally{t===this.dynamicMetricsRequest&&(this.dynamicMetricsRefreshInFlight=!1)}}isCurrentDynamicMetricsRequest(e,t){return t===this.dynamicMetricsRequest&&this.dynamicMetricsPollingMachineId===e&&this.isCurrentMachine(e)}applyDynamicMetrics(e){let t=this.systemInfo;t!==void 0&&(this.systemInfo={...t,memory:e.memory,network:{...t.network,...e.network}})}isCurrentMachine(e){return this.machineId===e&&this.context?.machine.id===e}render(){if(this.loading)return g`<section class="info-panel"><p class="muted">Loading system information…</p></section>`;if(this.error!==``)return g`<section class="info-panel">
|
|
1227
1227
|
<p class="error-text">Failed to load system information: ${this.error}</p>
|
|
1228
1228
|
<button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
|
|
1229
1229
|
</section>`;let e=this.systemInfo;return e===void 0?g`<section class="info-panel"><p class="muted">System information unavailable.</p></section>`:g`<section class="info-panel">
|
|
@@ -1477,12 +1477,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1477
1477
|
<div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
|
|
1478
1478
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
1479
1479
|
</section>
|
|
1480
|
-
`}function pC(){NS(()=>import(`./UnifiedDiffViewer-
|
|
1480
|
+
`}function pC(){NS(()=>import(`./UnifiedDiffViewer-CIfQkwSQ.js`),[],import.meta.url)}function mC(){NS(()=>Promise.resolve().then(()=>HB),void 0,import.meta.url)}function hC(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function gC(e){let t=_C(e);return g`
|
|
1481
1481
|
<p class="summary">
|
|
1482
1482
|
<span class="summary-branch">${t.branch}</span>
|
|
1483
1483
|
${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
|
|
1484
1484
|
</p>
|
|
1485
|
-
`}function _C(e){let t=e.branch??`detached`,n=e.ahead??0,r=e.behind??0;return{branch:n===0&&r===0?t:`${t} · ↑${String(n)} ↓${String(r)}`,...e.latestTag===void 0?{}:{latestTag:e.latestTag}}}function vC(e,t){return(t===`unmodified`?e:t).slice(0,1).toUpperCase()}var yC={apiVersion:1,name:`PI WEBUI Core`,activate:()=>({contributions:{actions:sS(),workspacePanels:sC()}})},bC={"--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-hierarchy-border":`#5c6b80`,"--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`},xC={"--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-hierarchy-border":`#5a6aa8`,"--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`},SC={"--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-hierarchy-border":`#8a7b64`,"--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`},CC={"--pi-bg":`#ffffff`,"--pi-surface":`#ffff87`,"--pi-surface-hover":`#f0e6d6`,"--pi-terminal-bg":`#15131b`,"--pi-terminal-text":`#fff9ee`,"--pi-border":`#c9bca8`,"--pi-border-muted":`#d8cdbc`,"--pi-hierarchy-border":`#6f6047`,"--pi-text":`#15131b`,"--pi-text-secondary":`#15131b`,"--pi-text-bright":`#15131b`,"--pi-muted":`#5f586a`,"--pi-dim":`#766f7e`,"--pi-accent":`#5FAFFF`,"--pi-accent-border":`#6430d8`,"--pi-selection-bg":`#00d700`,"--pi-success":`#5FD7FF`,"--pi-success-border":`#008c82`,"--pi-success-bg":`#e1f4ef`,"--pi-success-surface":`#d7f0ec`,"--pi-success-ring":`#008c8255`,"--pi-warning":`#FFD7FF`,"--pi-warning-border":`#b05f00`,"--pi-warning-surface":`#fff2d2`,"--pi-danger":`#FFAF00`,"--pi-purple":`#6430d8`,"--pi-purple-border":`#6430d8`,"--pi-purple-surface":`#FFAFFF`,"--pi-overlay":`#15131b66`,"--pi-shadow-soft":`#15131b22`,"--pi-shadow":`#15131b33`,"--pi-shadow-strong":`#15131b44`,"--pi-bg-overlay-soft":`#ffffffdd`,"--pi-bg-overlay":`#ffffffe6`,"--pi-success-bg-overlay":`#e1f4efee`,"--pi-terminal-selection":`#8d7b64`},wC={apiVersion:1,name:`PI WEBUI Themes`,activate:()=>({contributions:{themes:[{id:`pi-webui-dark`,name:`PI WEBUI Dark`,description:`Dark PI WEBUI palette.`,order:10,colorScheme:`dark`,tokens:xC},{id:`pi-webui-light`,name:`PI WEBUI Light`,description:`Light PI WEBUI palette.`,order:20,colorScheme:`light`,tokens:SC},{id:`classic`,name:`PI WEBUI Classic`,description:`The original PI WEBUI dark palette.`,order:30,colorScheme:`dark`,tokens:bC},{id:`eink-color-paper`,name:`E-Ink Color Paper`,description:`PI WEBUI Light baseline with targeted color e-ink adjustments.`,order:40,colorScheme:`light`,tokens:CC}],themePairs:[{id:`pi-webui`,name:`PI WEBUI`,description:`Follow the system light/dark preference with PI WEBUI themes.`,order:10,light:`pi-webui-light`,dark:`pi-webui-dark`}]}})},TC=/^[a-z][a-z0-9.-]*$/u;function EC(e){return TC.test(e)}var DC=`machine.`;function OC(e,t){if(e===``)throw Error(`Machine id is required`);if(!EC(t))throw Error(`Invalid PI WEBUI plugin id: ${t}`);return`${DC}${kC(e)}.${t}`}function kC(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function AC(e=`pi-webui-plugins/manifest.json`,t={}){let n=Jt(e),r=await NC(n);if(r===void 0)return[];let i=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=jC(e.module,n),a=IC(await(t.moduleLoader??MC)(r),r);i.push({id:t.machineId===void 0?e.id:OC(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){console.warn(`Failed to load PI WEBUI plugin ${e.module}`,t)}return i}function jC(e,t,n){return e.startsWith(`/`)?n===void 0?Jt(e):Jt(e,n):new URL(e,t).toString()}async function MC(e){return NS(()=>import(e),[],import.meta.url)}async function NC(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(`Failed to load plugin manifest: ${t.statusText}`);return PC(await t.json())}}function PC(e){if(!RC(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);return{plugins:e.plugins.map(e=>{if(!RC(e)||typeof e.id!=`string`||e.id===``||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);return{id:e.id,module:e.module,machineSpecific:FC(e.machineSpecific)}})}}function FC(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function IC(e,t){if(!RC(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(!LC(n))throw Error(`Plugin module ${t} default export is not a PiWebUiPlugin`);return n}function LC(e){return RC(e)&&e.apiVersion===1&&typeof e.name==`string`&&typeof e.activate==`function`}function RC(e){return typeof e==`object`&&!!e}var zC=/^[a-z][a-z0-9.-]*$/u,BC=/^[a-z][a-z0-9.-]*$/u,VC=new WeakMap,HC=new WeakMap,UC=new WeakMap,WC=class{constructor(){this.actions=[],this.workspacePanels=[],this.activityRailItems=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{id:t,plugin:n}=e;this.validatePluginId(t);let r=this.parseMachineSpecific(t,e.machineSpecific);if(this.pluginIds.has(t))throw Error(`Duplicate plugin id: ${t}`);if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,r))return;this.pluginIds.add(t);let i=n.apiVersion;if(i!==1)throw Error(`Unsupported plugin API version for ${t}: ${String(i)}`);let a=n.activate({apiVersion:1,pluginId:t,html:g,svg:_,capabilities:{activityRailItems:!0,sessionExtensionEntries:!0}}).contributions;for(let n of a.actions??[])this.actions.push(this.qualifyAction(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(t,n,e.machineId,e.sourcePluginId));for(let n of a.activityRailItems??[])this.activityRailItems.push(this.qualifyActivityRailItem(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(t,n,e.machineId,e.sourcePluginId));if(e.machineId===void 0){for(let e of a.themes??[])this.themes.push(this.qualifyTheme(t,e));for(let e of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(t,e));this.gatewayPluginIds.add(t),r&&this.gatewayMachineSpecificPluginIds.add(t)}else e.sourcePluginId!==void 0&&r&&ZC(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=$C(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=GC(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.group!==void 0&&(a.group=t.group),t.closesActionPalette!==void 0&&(a.closesActionPalette=t.closesActionPalette),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))}getActivityRailItems(){return[...this.activityRailItems].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title)||e.id.localeCompare(t.id))}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){let i=this.qualify(e,t.id);return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r){let i=this.qualify(e,t.id),a={pluginId:e,...r===void 0?{}:{sourcePluginId:r},localId:t.id,...n===void 0?{}:{machineId:n}},o=t.badge,s=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(s?.(KC(t,a))??!0),...o===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?o(KC(t,a)):void 0},render:e=>t.render(KC(e,a))}}qualifyActivityRailItem(e,t,n,r){let i=this.qualify(e,t.id),a=t.badge,o=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(o?.(qC(t,e))??!0),...a===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?a(qC(t,e)):void 0},render:i=>this.isContributionActive(e,n,i.machine.id,r)?t.render(qC(i,e)):g``}}qualifyWorkspaceLabelContribution(e,t,n,r){let i=this.qualify(e,t.id),a=t.visible,o=t.items;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(a?.(t)??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?o(t):[]}}qualifyTheme(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id}}qualifyThemePair(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t){this.validateLocalId(t);let n=`${e}:${t}`;if(this.contributionIds.has(n))throw Error(`Duplicate contribution id: ${n}`);return this.contributionIds.add(n),n}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)}validatePluginId(e){if(!zC.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!BC.test(e))throw Error(`Invalid contribution id: ${e}`)}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${QC(t)}`);return t}};function GC(e,t){return VC.get(e)?.(t)??e}function KC(e,t){return HC.get(e)?.(t)??e}function qC(e,t){return UC.get(e)?.(t)??e}function JC(e,t){return VC.set(e,t),e}function YC(e,t){return HC.set(e,t),e}function XC(e,t){return UC.set(e,t),e}function ZC(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function QC(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 $C(e){return e.state.selectedMachine?.id??`local`}var ew=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function tw(){return typeof window>`u`||!(`matchMedia`in window)?[]:ew.map(e=>window.matchMedia(e))}function nw(e,t=rw()){return e.some(e=>e.matches)||iw(t)}function rw(){return typeof navigator>`u`?void 0:navigator}function iw(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var aw=class{constructor(e=ow()){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 ow(){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 sw=`(max-width: 760px)`,cw=`(min-width: 1181px)`,lw=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onActivityRailDesktopMediaChange=e=>{this.isDesktopActivityRailLayout!==e.matches&&(this.isDesktopActivityRailLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=nw(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??dw(),this.activityRailDesktopMedia=t.activityRailDesktopMedia??uw(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??tw(),this.viewportPositionRepairer=t.viewportPositionRepairer??new aw,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isDesktopActivityRailLayout=this.activityRailDesktopMedia?.matches??!0,this.isPwaDisplayMode=nw(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange),this.activityRailDesktopMedia?.addEventListener(`change`,this.onActivityRailDesktopMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange),this.activityRailDesktopMedia?.removeEventListener(`change`,this.onActivityRailDesktopMediaChange);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(){return this.isMobileNavigationLayout?`navigation`:`chat`}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function uw(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(cw)}function dw(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(sw)}var fw=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new Sd,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??pw(),this.documentTarget=t.documentTarget??mw(),this.isDocumentVisible=t.isDocumentVisible??hw,this.scheduleFrame=t.scheduleFrame??gw}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 pw(){return typeof window>`u`?void 0:window}function mw(){return typeof document>`u`?void 0:document}function hw(){return typeof document>`u`||document.visibilityState===`visible`}function gw(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 _w=`pi-webui:speech-input-settings:`,vw=class{constructor(e,t={}){this.onRevision=e,this.closed=!1;let n=t.resolveAppUrl??Jt,r=t.createBroadcastChannel??yw;try{this.channel=r(`${_w}${n(``)}`),this.channel!==void 0&&(this.channel.onmessage=e=>{this.handleMessage(e.data)})}catch{this.channel=void 0}}publish(e){if(!(this.closed||!xw(e))){this.lastRevision=e;try{this.channel?.postMessage({contractVersion:1,revision:e})}catch{}}}close(){if(this.closed)return;this.closed=!0;let e=this.channel;this.channel=void 0,e!==void 0&&(e.onmessage=null,e.close())}handleMessage(e){this.closed||!bw(e)||e.revision!==this.lastRevision&&(this.lastRevision=e.revision,this.onRevision(e.revision))}};function yw(e){if(!(typeof BroadcastChannel>`u`))return new BroadcastChannel(e)}function bw(e){return!Sw(e)||Object.keys(e).length!==2?!1:e.contractVersion===1&&xw(e.revision)}function xw(e){return typeof e==`string`&&kn(e)}function Sw(e){return typeof e==`object`&&!!e}var Cw=[`machines`,`projects`,`workspaces`,`sessions`];function ww(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Tw(e,t){if(e!==`none`)return e??ww(t)}function Ew(e,t){return t.isMobileLayout?Tw(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Dw(e,t,n){return n.isMobileLayout?Tw(e,n.state)===t?`none`:t:e}function Ow(e,t,n){return n?t:e}function kw(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Mw(n)}function Aw(e){return Cw[Cw.indexOf(e)+1]}var jw=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Tw(this.expanded,this.getState())}isCollapsed(e){return Ew(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(Dw(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(kw(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(Ow(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Aw(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){Nw(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Mw(e){let t=new Set(e);return Cw.filter(e=>t.has(e))}function Nw(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var Pw=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){return[`shell`,Fw(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function Fw(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var Iw=`pi-webui:panel-sizes:v1`,Lw={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Rw=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??Qw(),this.panelSizes=Ww(this.storage)}hostConnected(){}constraints(e){return zw(e)}panelWidth(e,t){return Uw(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=Uw(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Jw(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Yw(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(){Gw(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${Zw(Uw(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${Zw(Uw(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function zw(e){return Lw[e]}function Bw(e,t,n){return e===`navigation`?n-t:t-n}function Vw(e,t,n,r,i=zw(e)){return Uw(e,t+Bw(e,n,r),i)}function Hw(e,t,n,r={}){let i=r.constraints??zw(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=Xw(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return Uw(e,t+a,i)}function Uw(e,t,n=zw(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function Ww(e=Qw()){try{let t=e?.getItem(Iw);return t==null||t===``?{}:Kw(JSON.parse(t))}catch{return{}}}function Gw(e,t=Qw()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Iw);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=Uw(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=Uw(`workspace`,e.workspacePanelWidth)),t.setItem(Iw,JSON.stringify(n))}catch{}}function Kw(e){if(!$w(e)||e.version!==1)return{};let t={},n=qw(e.navigationPanelWidth),r=qw(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=Uw(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=Uw(`workspace`,r)),t}function qw(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Jw(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Yw(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Xw(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 Zw(e){return`${String(Math.round(e))}px`}function Qw(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function $w(e){return typeof e==`object`&&!!e}function eT(){let e=new URLSearchParams(window.location.search);return{machineId:e.get(`machine`)??void 0,projectId:e.get(`project`)??void 0,workspaceId:e.get(`workspace`)??void 0,sessionId:e.get(`session`)??void 0,tool:nT(e.get(`tool`)),view:rT(e.get(`view`))}}function tT(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&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&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 nT(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:iT(e)?e:void 0}function rT(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:iT(e)?e:void 0}function iT(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function aT(){return sT(new URLSearchParams(window.location.search).get(`settings`))}function oT(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 sT(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`;if(e===`modeltiers`||e===`model-tiers`||e===`tiers`)return`modeltiers`;if(e===`utilitymodels`||e===`utility-models`||e===`utilities`)return`utilitymodels`}function cT(e,t){return t===void 0?e:e.map(e=>uT(e,t))}function lT(e,t){let n=new Set(xb(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return cT(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?dT(e):e)}function uT(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?dT(e):{...e,shortcut:n}}function dT(e){let t={...e};return delete t.shortcut,t}function fT(e,t){let n=t.api??Ac,r=t.pollIntervalMs??1e3,i=t.setTimeout??hT(),a=t.clearTimeout??gT();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:pT(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function pT(e,t,n,r,i){return mT(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&&mT(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function mT(e){return e.status===`succeeded`||e.status===`failed`}function hT(){return(e,t)=>globalThis.setTimeout(e,t)}function gT(){return e=>{globalThis.clearTimeout(e)}}var _T=16,vT=320,yT=240;function bT(e,t,n){let r=ST(e,n),i=CT(n.width,vT),a=CT(n.height,yT);return{...r,left:wT(r.left+t.x,i.margin,i.viewportSize-i.margin-r.width),top:wT(r.top+t.y,a.margin,a.viewportSize-a.margin-r.height)}}function xT(e,t,n){let r=ST(e,n),i=CT(n.width,vT),a=CT(n.height,yT);return{...r,width:wT(r.width+t.x,i.minSize,i.viewportSize-i.margin-r.left),height:wT(r.height+t.y,a.minSize,a.viewportSize-a.margin-r.top)}}function ST(e,t){let n=CT(t.width,vT),r=CT(t.height,yT),i=wT(e.width,n.minSize,n.maxSize),a=wT(e.height,r.minSize,r.maxSize);return{left:wT(e.left,n.margin,n.viewportSize-n.margin-i),top:wT(e.top,r.margin,r.viewportSize-r.margin-a),width:i,height:a}}function CT(e,t){let n=Math.max(0,e),r=Math.min(_T,n/2),i=n-r*2;return{viewportSize:n,margin:r,minSize:Math.min(t,i),maxSize:i}}function wT(e,t,n){return Math.max(t,Math.min(n,e))}var TT=`pi-webui:terminal-modal-preferences:v1`,ET={fontSize:16,opacity:94};function DT(e){return Math.max(10,Math.min(28,Math.round(e)))}function OT(e){return Math.max(20,Math.min(100,Math.round(e)))}function kT(e=NT()){if(e===void 0)return{...ET};try{return jT(e.getItem(TT))}catch{return{...ET}}}function AT(e,t=NT()){if(t!==void 0)try{t.setItem(TT,JSON.stringify({fontSize:DT(e.fontSize),opacity:OT(e.opacity)}))}catch{}}function jT(e){if(e===null)return{...ET};try{let t=JSON.parse(e);return PT(t)?{fontSize:MT(t.fontSize,ET.fontSize,DT),opacity:MT(t.opacity,ET.opacity,OT)}:{...ET}}catch{return{...ET}}}function MT(e,t,n){return typeof e==`number`&&Number.isFinite(e)?n(e):t}function NT(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function PT(e){return typeof e==`object`&&!!e}var FT=`pi-webui:terminal-tab-hidden`,IT=`pi-webui:info-tab-hidden`;function LT(e=VT()){return{terminalHidden:zT(e,FT),infoHidden:zT(e,IT)}}function RT(e,t=VT()){BT(t,FT,e.terminalHidden),BT(t,IT,e.infoHidden)}function zT(e,t){if(e===void 0)return!1;try{return e.getItem(t)===`true`}catch{return!1}}function BT(e,t,n){if(e!==void 0)try{n?e.setItem(t,`true`):e.removeItem(t)}catch{}}function VT(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}var HT=`PI WEBUI`;function UT(e){return e!==void 0&&e!==``?`${e} - ${HT}`:HT}function WT(e){let t=()=>{document.title!==e&&(document.title=e)};t();let n=new MutationObserver(t);return n.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>{n.disconnect()}}var GT=0,KT=120;function qT(e,t){return e.composedPath().some(e=>typeof HTMLElement>`u`||!(e instanceof HTMLElement)?!1:e.getRootNode()===t&&e.closest(`.action-menu`)!==null)}function JT(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?XT():YT(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-GT,f=n.top-c-GT;return[...d<KT&&f>d?[`bottom: ${ZT(a-n.top+GT)};`,`max-height: ${ZT(Math.max(0,f))};`]:[`top: ${ZT(n.bottom+GT)};`,`max-height: ${ZT(Math.max(0,d))};`],`right: ${ZT(Math.max(0,i-u))};`,`max-width: ${ZT(Math.max(0,u-o))};`].join(` `)}function YT(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():XT()}function XT(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function ZT(e){return`${String(Math.round(e))}px`}function QT(e,t=`Active`,n){if(e!==void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}>${n===void 0?null:g`<span class="activity-indicator-count" aria-hidden="true">${String(n)}</span>`}</span>`}function $T(e,t=`Active`){let n=QT(e,t);if(n!==void 0)return g`<span class="action-activity">${n}</span>`}function eE(e){if(e.length!==0)return g`<span class="action-activities">${e.map(e=>QT(e.kind,e.label,e.count))}</span>`}var tE=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function nE(e){return e.composedPath().some(e=>rE(e,tE))}function rE(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 iE(e,t){nE(e)||t()}function aE(e,t){return nE(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?sE(e,()=>{cE(e.currentTarget,-1)}):e.key===`ArrowDown`?sE(e,()=>{cE(e.currentTarget,1)}):e.key===`Home`?sE(e,()=>{lE(e.currentTarget,0)}):e.key===`End`?sE(e,()=>{lE(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?sE(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?sE(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&sE(e,t.cancel)}function oE(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 sE(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function cE(e,t){let n=dE(e),r=pE(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||uE(n,i+t)}function lE(e,t){let n=dE(e);n.length!==0&&uE(n,t<0?n.length-1:t)}function uE(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function dE(e){let t=pE(e)?.getRootNode();return t===void 0||!fE(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function fE(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function pE(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var mE=class extends y{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.openMenuMachineId!==void 0&&!this.machines.some(e=>e.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,oE(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1485
|
+
`}function _C(e){let t=e.branch??`detached`,n=e.ahead??0,r=e.behind??0;return{branch:n===0&&r===0?t:`${t} · ↑${String(n)} ↓${String(r)}`,...e.latestTag===void 0?{}:{latestTag:e.latestTag}}}function vC(e,t){return(t===`unmodified`?e:t).slice(0,1).toUpperCase()}var yC={apiVersion:1,name:`PI WEBUI Core`,activate:()=>({contributions:{actions:sS(),workspacePanels:sC()}})},bC={"--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-hierarchy-border":`#5c6b80`,"--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`},xC={"--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-hierarchy-border":`#5a6aa8`,"--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`},SC={"--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-hierarchy-border":`#8a7b64`,"--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`},CC={"--pi-bg":`#ffffff`,"--pi-surface":`#ffff87`,"--pi-surface-hover":`#f0e6d6`,"--pi-terminal-bg":`#15131b`,"--pi-terminal-text":`#fff9ee`,"--pi-border":`#c9bca8`,"--pi-border-muted":`#d8cdbc`,"--pi-hierarchy-border":`#6f6047`,"--pi-text":`#15131b`,"--pi-text-secondary":`#15131b`,"--pi-text-bright":`#15131b`,"--pi-muted":`#5f586a`,"--pi-dim":`#766f7e`,"--pi-accent":`#5FAFFF`,"--pi-accent-border":`#6430d8`,"--pi-selection-bg":`#00d700`,"--pi-success":`#5FD7FF`,"--pi-success-border":`#008c82`,"--pi-success-bg":`#e1f4ef`,"--pi-success-surface":`#d7f0ec`,"--pi-success-ring":`#008c8255`,"--pi-warning":`#FFD7FF`,"--pi-warning-border":`#b05f00`,"--pi-warning-surface":`#fff2d2`,"--pi-danger":`#FFAF00`,"--pi-purple":`#6430d8`,"--pi-purple-border":`#6430d8`,"--pi-purple-surface":`#FFAFFF`,"--pi-overlay":`#15131b66`,"--pi-shadow-soft":`#15131b22`,"--pi-shadow":`#15131b33`,"--pi-shadow-strong":`#15131b44`,"--pi-bg-overlay-soft":`#ffffffdd`,"--pi-bg-overlay":`#ffffffe6`,"--pi-success-bg-overlay":`#e1f4efee`,"--pi-terminal-selection":`#8d7b64`},wC={apiVersion:1,name:`PI WEBUI Themes`,activate:()=>({contributions:{themes:[{id:`pi-webui-dark`,name:`PI WEBUI Dark`,description:`Dark PI WEBUI palette.`,order:10,colorScheme:`dark`,tokens:xC},{id:`pi-webui-light`,name:`PI WEBUI Light`,description:`Light PI WEBUI palette.`,order:20,colorScheme:`light`,tokens:SC},{id:`classic`,name:`PI WEBUI Classic`,description:`The original PI WEBUI dark palette.`,order:30,colorScheme:`dark`,tokens:bC},{id:`eink-color-paper`,name:`E-Ink Color Paper`,description:`PI WEBUI Light baseline with targeted color e-ink adjustments.`,order:40,colorScheme:`light`,tokens:CC}],themePairs:[{id:`pi-webui`,name:`PI WEBUI`,description:`Follow the system light/dark preference with PI WEBUI themes.`,order:10,light:`pi-webui-light`,dark:`pi-webui-dark`}]}})},TC=/^[a-z][a-z0-9.-]*$/u;function EC(e){return TC.test(e)}var DC=`machine.`;function OC(e,t){if(e===``)throw Error(`Machine id is required`);if(!EC(t))throw Error(`Invalid PI WEBUI plugin id: ${t}`);return`${DC}${kC(e)}.${t}`}function kC(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function AC(e=`pi-webui-plugins/manifest.json`,t={}){let n=Jt(e),r=await NC(n);if(r===void 0)return[];let i=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=jC(e.module,n),a=IC(await(t.moduleLoader??MC)(r),r);i.push({id:t.machineId===void 0?e.id:OC(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){console.warn(`Failed to load PI WEBUI plugin ${e.module}`,t)}return i}function jC(e,t,n){return e.startsWith(`/`)?n===void 0?Jt(e):Jt(e,n):new URL(e,t).toString()}async function MC(e){return NS(()=>import(e),[],import.meta.url)}async function NC(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(`Failed to load plugin manifest: ${t.statusText}`);return PC(await t.json())}}function PC(e){if(!RC(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);return{plugins:e.plugins.map(e=>{if(!RC(e)||typeof e.id!=`string`||e.id===``||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);return{id:e.id,module:e.module,machineSpecific:FC(e.machineSpecific)}})}}function FC(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function IC(e,t){if(!RC(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(!LC(n))throw Error(`Plugin module ${t} default export is not a PiWebUiPlugin`);return n}function LC(e){return RC(e)&&e.apiVersion===1&&typeof e.name==`string`&&typeof e.activate==`function`}function RC(e){return typeof e==`object`&&!!e}var zC=/^[a-z][a-z0-9.-]*$/u,BC=/^[a-z][a-z0-9.-]*$/u,VC=new WeakMap,HC=new WeakMap,UC=new WeakMap,WC=class{constructor(){this.actions=[],this.workspacePanels=[],this.activityRailItems=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{id:t,plugin:n}=e;this.validatePluginId(t);let r=this.parseMachineSpecific(t,e.machineSpecific);if(this.pluginIds.has(t))throw Error(`Duplicate plugin id: ${t}`);if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,r))return;this.pluginIds.add(t);let i=n.apiVersion;if(i!==1)throw Error(`Unsupported plugin API version for ${t}: ${String(i)}`);let a=n.activate({apiVersion:1,pluginId:t,html:g,svg:_,capabilities:{activityRailItems:!0,sessionExtensionEntries:!0}}).contributions;for(let n of a.actions??[])this.actions.push(this.qualifyAction(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(t,n,e.machineId,e.sourcePluginId));for(let n of a.activityRailItems??[])this.activityRailItems.push(this.qualifyActivityRailItem(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(t,n,e.machineId,e.sourcePluginId));if(e.machineId===void 0){for(let e of a.themes??[])this.themes.push(this.qualifyTheme(t,e));for(let e of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(t,e));this.gatewayPluginIds.add(t),r&&this.gatewayMachineSpecificPluginIds.add(t)}else e.sourcePluginId!==void 0&&r&&ZC(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=$C(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=GC(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.group!==void 0&&(a.group=t.group),t.closesActionPalette!==void 0&&(a.closesActionPalette=t.closesActionPalette),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))}getActivityRailItems(){return[...this.activityRailItems].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title)||e.id.localeCompare(t.id))}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){let i=this.qualify(e,t.id);return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r){let i=this.qualify(e,t.id),a={pluginId:e,...r===void 0?{}:{sourcePluginId:r},localId:t.id,...n===void 0?{}:{machineId:n}},o=t.badge,s=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(s?.(KC(t,a))??!0),...o===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?o(KC(t,a)):void 0},render:e=>t.render(KC(e,a))}}qualifyActivityRailItem(e,t,n,r){let i=this.qualify(e,t.id),a=t.badge,o=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(o?.(qC(t,e))??!0),...a===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?a(qC(t,e)):void 0},render:i=>this.isContributionActive(e,n,i.machine.id,r)?t.render(qC(i,e)):g``}}qualifyWorkspaceLabelContribution(e,t,n,r){let i=this.qualify(e,t.id),a=t.visible,o=t.items;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(a?.(t)??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?o(t):[]}}qualifyTheme(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id}}qualifyThemePair(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t){this.validateLocalId(t);let n=`${e}:${t}`;if(this.contributionIds.has(n))throw Error(`Duplicate contribution id: ${n}`);return this.contributionIds.add(n),n}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)}validatePluginId(e){if(!zC.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!BC.test(e))throw Error(`Invalid contribution id: ${e}`)}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${QC(t)}`);return t}};function GC(e,t){return VC.get(e)?.(t)??e}function KC(e,t){return HC.get(e)?.(t)??e}function qC(e,t){return UC.get(e)?.(t)??e}function JC(e,t){return VC.set(e,t),e}function YC(e,t){return HC.set(e,t),e}function XC(e,t){return UC.set(e,t),e}function ZC(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function QC(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 $C(e){return e.state.selectedMachine?.id??`local`}var ew=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function tw(){return typeof window>`u`||!(`matchMedia`in window)?[]:ew.map(e=>window.matchMedia(e))}function nw(e,t=rw()){return e.some(e=>e.matches)||iw(t)}function rw(){return typeof navigator>`u`?void 0:navigator}function iw(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var aw=class{constructor(e=ow()){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 ow(){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 sw=`(max-width: 760px)`,cw=`(min-width: 1181px)`,lw=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onActivityRailDesktopMediaChange=e=>{this.isDesktopActivityRailLayout!==e.matches&&(this.isDesktopActivityRailLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=nw(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??dw(),this.activityRailDesktopMedia=t.activityRailDesktopMedia??uw(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??tw(),this.viewportPositionRepairer=t.viewportPositionRepairer??new aw,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isDesktopActivityRailLayout=this.activityRailDesktopMedia?.matches??!0,this.isPwaDisplayMode=nw(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange),this.activityRailDesktopMedia?.addEventListener(`change`,this.onActivityRailDesktopMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange),this.activityRailDesktopMedia?.removeEventListener(`change`,this.onActivityRailDesktopMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInRail(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&!this.isDesktopActivityRailLayout}defaultRouteView(){return this.isMobileNavigationLayout?`navigation`:`chat`}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function uw(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(cw)}function dw(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(sw)}var fw=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new Sd,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??pw(),this.documentTarget=t.documentTarget??mw(),this.isDocumentVisible=t.isDocumentVisible??hw,this.scheduleFrame=t.scheduleFrame??gw}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 pw(){return typeof window>`u`?void 0:window}function mw(){return typeof document>`u`?void 0:document}function hw(){return typeof document>`u`||document.visibilityState===`visible`}function gw(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 _w=`pi-webui:speech-input-settings:`,vw=class{constructor(e,t={}){this.onRevision=e,this.closed=!1;let n=t.resolveAppUrl??Jt,r=t.createBroadcastChannel??yw;try{this.channel=r(`${_w}${n(``)}`),this.channel!==void 0&&(this.channel.onmessage=e=>{this.handleMessage(e.data)})}catch{this.channel=void 0}}publish(e){if(!(this.closed||!xw(e))){this.lastRevision=e;try{this.channel?.postMessage({contractVersion:1,revision:e})}catch{}}}close(){if(this.closed)return;this.closed=!0;let e=this.channel;this.channel=void 0,e!==void 0&&(e.onmessage=null,e.close())}handleMessage(e){this.closed||!bw(e)||e.revision!==this.lastRevision&&(this.lastRevision=e.revision,this.onRevision(e.revision))}};function yw(e){if(!(typeof BroadcastChannel>`u`))return new BroadcastChannel(e)}function bw(e){return!Sw(e)||Object.keys(e).length!==2?!1:e.contractVersion===1&&xw(e.revision)}function xw(e){return typeof e==`string`&&kn(e)}function Sw(e){return typeof e==`object`&&!!e}var Cw=[`machines`,`projects`,`workspaces`,`sessions`];function ww(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Tw(e,t){if(e!==`none`)return e??ww(t)}function Ew(e,t){return t.isMobileLayout?Tw(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Dw(e,t,n){return n.isMobileLayout?Tw(e,n.state)===t?`none`:t:e}function Ow(e,t,n){return n?t:e}function kw(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Mw(n)}function Aw(e){return Cw[Cw.indexOf(e)+1]}var jw=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Tw(this.expanded,this.getState())}isCollapsed(e){return Ew(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(Dw(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(kw(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(Ow(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Aw(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){Nw(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Mw(e){let t=new Set(e);return Cw.filter(e=>t.has(e))}function Nw(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var Pw=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){return[`shell`,Fw(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function Fw(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var Iw=`pi-webui:panel-sizes:v1`,Lw={navigation:{minWidth:324,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Rw=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??Qw(),this.panelSizes=Ww(this.storage)}hostConnected(){}constraints(e){return zw(e)}panelWidth(e,t){return Uw(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=Uw(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Jw(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Yw(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(){Gw(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${Zw(Uw(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${Zw(Uw(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function zw(e){return Lw[e]}function Bw(e,t,n){return e===`navigation`?n-t:t-n}function Vw(e,t,n,r,i=zw(e)){return Uw(e,t+Bw(e,n,r),i)}function Hw(e,t,n,r={}){let i=r.constraints??zw(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=Xw(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return Uw(e,t+a,i)}function Uw(e,t,n=zw(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function Ww(e=Qw()){try{let t=e?.getItem(Iw);return t==null||t===``?{}:Kw(JSON.parse(t))}catch{return{}}}function Gw(e,t=Qw()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Iw);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=Uw(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=Uw(`workspace`,e.workspacePanelWidth)),t.setItem(Iw,JSON.stringify(n))}catch{}}function Kw(e){if(!$w(e)||e.version!==1)return{};let t={},n=qw(e.navigationPanelWidth),r=qw(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=Uw(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=Uw(`workspace`,r)),t}function qw(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Jw(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Yw(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Xw(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 Zw(e){return`${String(Math.round(e))}px`}function Qw(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function $w(e){return typeof e==`object`&&!!e}function eT(){let e=new URLSearchParams(window.location.search);return{machineId:e.get(`machine`)??void 0,projectId:e.get(`project`)??void 0,workspaceId:e.get(`workspace`)??void 0,sessionId:e.get(`session`)??void 0,tool:nT(e.get(`tool`)),view:rT(e.get(`view`))}}function tT(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&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&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 nT(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:iT(e)?e:void 0}function rT(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:iT(e)?e:void 0}function iT(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function aT(){return sT(new URLSearchParams(window.location.search).get(`settings`))}function oT(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 sT(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`;if(e===`modeltiers`||e===`model-tiers`||e===`tiers`)return`modeltiers`;if(e===`utilitymodels`||e===`utility-models`||e===`utilities`)return`utilitymodels`}function cT(e,t){return t===void 0?e:e.map(e=>uT(e,t))}function lT(e,t){let n=new Set(xb(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return cT(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?dT(e):e)}function uT(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?dT(e):{...e,shortcut:n}}function dT(e){let t={...e};return delete t.shortcut,t}function fT(e,t){let n=t.api??Ac,r=t.pollIntervalMs??1e3,i=t.setTimeout??hT(),a=t.clearTimeout??gT();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:pT(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function pT(e,t,n,r,i){return mT(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&&mT(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function mT(e){return e.status===`succeeded`||e.status===`failed`}function hT(){return(e,t)=>globalThis.setTimeout(e,t)}function gT(){return e=>{globalThis.clearTimeout(e)}}var _T=16,vT=320,yT=240;function bT(e,t,n){let r=ST(e,n),i=CT(n.width,vT),a=CT(n.height,yT);return{...r,left:wT(r.left+t.x,i.margin,i.viewportSize-i.margin-r.width),top:wT(r.top+t.y,a.margin,a.viewportSize-a.margin-r.height)}}function xT(e,t,n){let r=ST(e,n),i=CT(n.width,vT),a=CT(n.height,yT);return{...r,width:wT(r.width+t.x,i.minSize,i.viewportSize-i.margin-r.left),height:wT(r.height+t.y,a.minSize,a.viewportSize-a.margin-r.top)}}function ST(e,t){let n=CT(t.width,vT),r=CT(t.height,yT),i=wT(e.width,n.minSize,n.maxSize),a=wT(e.height,r.minSize,r.maxSize);return{left:wT(e.left,n.margin,n.viewportSize-n.margin-i),top:wT(e.top,r.margin,r.viewportSize-r.margin-a),width:i,height:a}}function CT(e,t){let n=Math.max(0,e),r=Math.min(_T,n/2),i=n-r*2;return{viewportSize:n,margin:r,minSize:Math.min(t,i),maxSize:i}}function wT(e,t,n){return Math.max(t,Math.min(n,e))}var TT=`pi-webui:terminal-modal-preferences:v1`,ET={fontSize:16,opacity:94};function DT(e){return Math.max(10,Math.min(28,Math.round(e)))}function OT(e){return Math.max(20,Math.min(100,Math.round(e)))}function kT(e=NT()){if(e===void 0)return{...ET};try{return jT(e.getItem(TT))}catch{return{...ET}}}function AT(e,t=NT()){if(t!==void 0)try{t.setItem(TT,JSON.stringify({fontSize:DT(e.fontSize),opacity:OT(e.opacity)}))}catch{}}function jT(e){if(e===null)return{...ET};try{let t=JSON.parse(e);return PT(t)?{fontSize:MT(t.fontSize,ET.fontSize,DT),opacity:MT(t.opacity,ET.opacity,OT)}:{...ET}}catch{return{...ET}}}function MT(e,t,n){return typeof e==`number`&&Number.isFinite(e)?n(e):t}function NT(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function PT(e){return typeof e==`object`&&!!e}var FT=`pi-webui:terminal-tab-hidden`,IT=`pi-webui:info-tab-hidden`;function LT(e=VT()){return{terminalHidden:zT(e,FT),infoHidden:zT(e,IT)}}function RT(e,t=VT()){BT(t,FT,e.terminalHidden),BT(t,IT,e.infoHidden)}function zT(e,t){if(e===void 0)return!1;try{return e.getItem(t)===`true`}catch{return!1}}function BT(e,t,n){if(e!==void 0)try{n?e.setItem(t,`true`):e.removeItem(t)}catch{}}function VT(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}var HT=`PI WEBUI`;function UT(e){return e!==void 0&&e!==``?`${e} - ${HT}`:HT}function WT(e){let t=()=>{document.title!==e&&(document.title=e)};t();let n=new MutationObserver(t);return n.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>{n.disconnect()}}var GT=0,KT=120;function qT(e,t){return e.composedPath().some(e=>typeof HTMLElement>`u`||!(e instanceof HTMLElement)?!1:e.getRootNode()===t&&e.closest(`.action-menu`)!==null)}function JT(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?XT():YT(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-GT,f=n.top-c-GT;return[...d<KT&&f>d?[`bottom: ${ZT(a-n.top+GT)};`,`max-height: ${ZT(Math.max(0,f))};`]:[`top: ${ZT(n.bottom+GT)};`,`max-height: ${ZT(Math.max(0,d))};`],`right: ${ZT(Math.max(0,i-u))};`,`max-width: ${ZT(Math.max(0,u-o))};`].join(` `)}function YT(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():XT()}function XT(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function ZT(e){return`${String(Math.round(e))}px`}function QT(e,t=`Active`,n){if(e!==void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}>${n===void 0?null:g`<span class="activity-indicator-count" aria-hidden="true">${String(n)}</span>`}</span>`}function $T(e,t=`Active`){let n=QT(e,t);if(n!==void 0)return g`<span class="action-activity">${n}</span>`}function eE(e){if(e.length!==0)return g`<span class="action-activities">${e.map(e=>QT(e.kind,e.label,e.count))}</span>`}var tE=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function nE(e){return e.composedPath().some(e=>rE(e,tE))}function rE(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 iE(e,t){nE(e)||t()}function aE(e,t){return nE(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?sE(e,()=>{cE(e.currentTarget,-1)}):e.key===`ArrowDown`?sE(e,()=>{cE(e.currentTarget,1)}):e.key===`Home`?sE(e,()=>{lE(e.currentTarget,0)}):e.key===`End`?sE(e,()=>{lE(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?sE(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?sE(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&sE(e,t.cancel)}function oE(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 sE(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function cE(e,t){let n=dE(e),r=pE(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||uE(n,i+t)}function lE(e,t){let n=dE(e);n.length!==0&&uE(n,t<0?n.length-1:t)}function uE(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function dE(e){let t=pE(e)?.getRootNode();return t===void 0||!fE(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function fE(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function pE(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var mE=class extends y{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.openMenuMachineId!==void 0&&!this.machines.some(e=>e.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,oE(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1486
1486
|
<section>
|
|
1487
1487
|
<h2>${this.renderHeading()}</h2>
|
|
1488
1488
|
${this.collapsed?null:g`
|
|
@@ -2871,7 +2871,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2871
2871
|
`,n),i=e.slice(n,r<0?e.length:r),a=/^ {0,3}(`{3,}|~{3,})/u.exec(i)?.[1];if(t!==void 0){a?.startsWith(t.character)===!0&&a.length>=t.length&&(t=void 0);continue}let o=a?.startsWith("`")===!0?"`":a?.startsWith(`~`)===!0?`~`:void 0;if(o!==void 0&&a!==void 0){t={character:o,length:a.length};continue}if($k(e.slice(n))!==void 0)return n}}function Qk(e,t){let n=$k(e);if(n!==void 0)return{type:`latex-display`,raw:n.raw,tex:n.tex,displayMode:!0}}function $k(e){let t=e.indexOf(`
|
|
2872
2872
|
`),n=t<0?e:e.slice(0,t),r=eA(n);if(r===void 0)return;let i=n.slice(r.delimiterEnd).replace(/^[ \t]+/u,``);if(i!==``){let a=nA(i,r.delimiter);if(a<0)return;let o=i.slice(0,a);if(o.length===0||o.length>Ik)return;let s=o.replace(/[ \t]+$/u,``);if(s.trim()===``||/^[ \t]*$/u.exec(i.slice(a+r.delimiter.length))===null)return;let c=t<0?n.length:t+1;return{raw:e.slice(0,c),tex:s}}if(t<0)return;let a=[],o=t+1,s=0;for(;o<=e.length;){let t=e.indexOf(`
|
|
2873
2873
|
`,o),n=t<0?e.length:t,i=e.slice(o,n);if(tA(i,r.delimiter)){if(a.length===0||a.every(e=>e.trim()===``))return;let r=t<0?n:t+1;return{raw:e.slice(0,r),tex:a.join(`
|
|
2874
|
-
`)}}if(rA(i)||(a.push(i),s+=i.length+ +(a.length>1),s>Ik)||t<0)return;o=t+1}}function eA(e){let t=/^( {0,3})(\$\$|\\\[)([ \t]*)$/u.exec(e);if(t!==null){let e=t[2];return e!==`$$`&&e!==`\\[`?void 0:{delimiter:e,delimiterEnd:t[0].length}}let n=/^( {0,3})(\$\$|\\\[)/u.exec(e);if(n===null)return;let r=n[2];if(!(r!==`$$`&&r!==`\\[`))return{delimiter:r,delimiterEnd:n[0].length}}function tA(e,t){return RegExp(`^ {0,3}${t===`$$`?`\\$\\$`:`\\\\\\]`}[ \\t]*$`,`u`).test(e)}function nA(e,t){let n=t===`$$`?`$$`:`\\]`,r=e.slice(0,Ik+n.length),i=0;for(;i<r.length;){let t=r.indexOf(n,i);if(t<0||t>Ik)return-1;if(/^[ \t]*$/u.test(e.slice(t+n.length)))return t;i=t+n.length}return-1}function rA(e){return/^ {0,3}(?:```|~~~)/u.test(e)}function iA(e){return aA(e),e}function aA(e){for(let t of e)oA(t)}function oA(e){if(lA(e,`paragraph`)||lA(e,`heading`)){e.tokens=cA(e.tokens);return}if(lA(e,`blockquote`)){aA(e.tokens);return}if(lA(e,`list`)){for(let t of e.items)aA(t.tokens);return}if(lA(e,`list_item`)){sA(e.tokens);return}if(lA(e,`text`)&&e.tokens!==void 0){e.tokens=cA(e.tokens);return}if(lA(e,`table`)){for(let t of e.header)t.tokens=cA(t.tokens);for(let t of e.rows)for(let e of t)e.tokens=cA(e.tokens)}}function sA(e){for(let t of e)lA(t,`text`)&&t.tokens!==void 0?t.tokens=cA(t.tokens):oA(t)}function cA(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===void 0)break;if(uA(r)){let r=[];for(;n<e.length;){let t=e[n];if(t===void 0||!uA(t))break;r.push(t),n+=1}t.push(...dA(r));continue}(lA(r,`em`)||lA(r,`strong`)||lA(r,`del`)||lA(r,`text`)&&r.tokens!==void 0)&&(r.tokens=cA(r.tokens)),t.push(r),n+=1}return t}function lA(e,t){return e.type===t}function uA(e){return lA(e,`escape`)||lA(e,`text`)&&e.tokens===void 0}function dA(e){let t=e.map(e=>e.raw).join(``);if(!qk(t))return e;let n=mA(t);if(n.length===0)return e;let r=fA(e),i={index:0},a=[],o=0;for(let e of n){pA(a,r,i,o,e.start);let n=t.slice(e.start,e.end);e.kind===`math`?a.push({type:e.displayMode===!0?`latex-display`:`latex-inline`,raw:n,tex:e.tex??``,displayMode:e.displayMode===!0}):a.push({type:`latex-inline-literal`,raw:n}),o=e.end}return pA(a,r,i,o,t.length),a}function fA(e){let t=[],n=0;for(let r of e){let e=n+r.raw.length;t.push({token:r,start:n,end:e}),n=e}return t}function pA(e,t,n,r,i){if(!(r>=i)){for(;n.index<t.length;){let e=t[n.index];if(e===void 0||e.end>r)break;n.index+=1}for(;n.index<t.length;n.index+=1){let a=t[n.index];if(a===void 0||a.start>=i)break;let o=Math.max(r,a.start)-a.start,s=Math.min(i,a.end)-a.start;if(o===0&&s===a.token.raw.length)e.push(a.token);else{let t=a.token.raw.slice(o,s),n=a.token.text.slice(o,s);e.push({type:`text`,raw:t,text:n.length===t.length?n:t,escaped:a.token.type===`text`&&a.token.escaped})}if(a.end>i)break}}}function mA(e){let t={head:void 0,tail:void 0},n=0,r,i,a,o,s=!1,c=!1;for(let l=0;l<e.length;l+=1){r=vA(r),i=vA(i),a=vA(a),o=vA(o),r!==void 0&&l-r.start-1>Ik&&(gA(t,r.placeholder),r=void 0,s=!0),i!==void 0&&l-i.start-2>Ik&&(gA(t,i.placeholder),i=void 0,c=!0),a!==void 0&&l-a.start-2>Ik&&(a=void 0),o!==void 0&&l-o.start-2>Ik&&(o=void 0);let u=e[l];if(u===`\\`){if(n+=1,n%2==1){let n=e[l+1];if(n===`(`||n===`)`||n===`[`||n===`]`){let r=hA(t,l,l+2,`literal`);if(n===`(`)a??={start:l,placeholder:r};else if(n===`)`&&a!==void 0){let n=e.slice(a.start+2,l);n.length<=Ik&&n.length>0&&n.trim()!==``&&!/\s/u.test(n[0]??``)&&!/\s/u.test(n.at(-1)??``)&&SA(e,a.start)&&CA(e,l+2)&&_A(t,a.placeholder,l+2,`math`,n,!1),a=void 0}else if(n===`[`)o??={start:l,placeholder:r};else if(n===`]`&&o!==void 0){let n=e.slice(o.start+2,l);n.length<=Ik&&n.length>0&&n.trim()!==``&&_A(t,o.placeholder,l+2,`literal`),o=void 0}}}continue}if(u===`$`){let a=n%2==1;if(e[l+1]===`$`){if(!a){if(i===void 0&&!c)i={start:l,placeholder:hA(t,l,l+2,`literal`)};else if(i!==void 0){let n=e.slice(i.start+2,l);n.length<=Ik&&n.trim()!==``?_A(t,i.placeholder,l+2,`literal`):(gA(t,i.placeholder),n.length>Ik&&(c=!0)),i=void 0}}l+=1,n=0;continue}if(!a&&!s)if(r===void 0)bA(e,l)&&(r={start:l,placeholder:hA(t,l,l+1,`literal`)});else{let n=e.slice(r.start+1,l);xA(e,r.start,l,n)?(_A(t,r.placeholder,l+1,`math`,n,!1),r=void 0):(gA(t,r.placeholder),r=void 0,bA(e,l)&&(r={start:l,placeholder:hA(t,l,l+1,`literal`)}))}n=0;continue}n=0}return r!==void 0&&gA(t,r.placeholder),i!==void 0&&gA(t,i.placeholder),EA(yA(t))}function hA(e,t,n,r){let i={start:t,end:n,kind:r,linked:!0,previous:e.tail,next:void 0};return e.tail===void 0?e.head=i:e.tail.next=i,e.tail=i,i}function gA(e,t){t.linked&&=(t.previous===void 0?e.head=t.next:t.previous.next=t.next,t.next===void 0?e.tail=t.previous:t.next.previous=t.previous,t.previous=void 0,t.next=void 0,!1)}function _A(e,t,n,r,i,a){let o=t.next;for(;o!==void 0&&o.start<n;){let t=o.next;gA(e,o),o=t}t.end=n,t.kind=r,i===void 0?delete t.tex:t.tex=i,a===void 0?delete t.displayMode:t.displayMode=a}function vA(e){return e?.placeholder.linked===!0?e:void 0}function yA(e){let t=[];for(let n=e.head;n!==void 0;n=n.next){let e={start:n.start,end:n.end,kind:n.kind};n.tex!==void 0&&(e.tex=n.tex),n.displayMode!==void 0&&(e.displayMode=n.displayMode),t.push(e)}return t}function bA(e,t){let n=e[t+1];return SA(e,t)&&n!==void 0&&!/\s/u.test(n)}function xA(e,t,n,r){return n>t+1&&r.length>0&&!/\s/u.test(r.at(-1)??``)&&CA(e,n+1)}function SA(e,t){if(t<=0)return!0;let n=t-1,r=TA(e.charCodeAt(n))?n-1:n;return wA(e.codePointAt(r))}function CA(e,t){return wA(e.codePointAt(t))}function wA(e){return e===void 0||/[\s\p{P}\p{S}]/u.test(String.fromCodePoint(e))}function TA(e){return e>=56320&&e<=57343}function EA(e){let t=[];for(let n of e){let e=t.at(-1);e?.kind===`literal`&&n.kind===`literal`&&e.end===n.start?e.end=n.end:t.push({...n})}return t}function DA(e,t,n){if(e.type===`latex-inline-literal`)return Wk(e.raw);if(e.type===`latex-block-literal`)return`<p>${Wk(e.raw)}</p>`;let r=OA(e);if(r===void 0)return``;if(!kA(r.tex,t))return VA(r);let i;try{i=n(r.tex,{displayMode:r.displayMode})}catch{return VA(r)}if(!AA(i,t))return VA(r);let a=`aria-label="${Gk(r.tex)}"`;return r.displayMode?`<div class="math-display" role="img" ${a}>${i}</div>`:`<span class="math-inline" role="img" ${a}>${i}</span>`}function OA(e){if(e.type!==`latex-inline`&&e.type!==`latex-display`)return;let t=e,n=t.tex,r=t.displayMode;if(!(typeof n!=`string`||typeof r!=`boolean`))return{type:e.type,raw:e.raw,tex:n,displayMode:r}}function kA(e,t){return t.outputAdmissionClosed||e.length>Lk||t.mathSourceUnits+e.length>Rk||!jA(e)?!1:(t.mathSourceUnits+=e.length,!0)}function AA(e,t){return e.length>Uk||t.mathOutputUnits+e.length>Hk?(t.outputAdmissionClosed=!0,!1):(t.mathOutputUnits+=e.length,!0)}function jA(e){let t=0,n=0,r=0;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`\\`){let t=i;for(;t<e.length&&e[t]===`\\`;)t+=1;let a=t-i;if(a>=2&&(r+=Math.floor(a/2)),r>Vk)return!1;if(a%2==1){let r=e[t];if(/[A-Za-z@]/u.test(r??``)){n+=1;let r=MA(e,t),a=e.slice(t-1,r);if(NA(a)||!LA(e,a,r))return!1;i=r-1}else i=t}else i=t-1;continue}if(a===`{`){if(t+=1,t>zk)return!1}else if(a===`}`)t=Math.max(0,t-1);else if(a===`&`&&(r+=1,r>Vk))return!1}return n<=Bk}function MA(e,t){let n=t;for(;n<e.length&&/[A-Za-z@]/u.test(e[n]??``);)n+=1;return n}function NA(e){return[`\\def`,`\\gdef`,`\\edef`,`\\xdef`,`\\let`,`\\newcommand`,`\\renewcommand`,`\\href`,`\\url`,`\\style`,`\\class`,`\\cssId`,`\\bbox`,`\\unicode`,`\\definecolor`].includes(e)}var PA={"\\color":{modelBracket:!0,colorArgs:1},"\\textcolor":{modelBracket:!0,colorArgs:1},"\\colorbox":{modelBracket:!1,colorArgs:1},"\\fcolorbox":{modelBracket:!1,colorArgs:2},"\\rowcolor":{modelBracket:!0,colorArgs:1},"\\cellcolor":{modelBracket:!0,colorArgs:1},"\\columncolor":{modelBracket:!0,colorArgs:1}},FA=/^(?:rgb|RGB|gray)$/u,IA=/^[A-Za-z0-9#%(),.!\s-]+$/u;function LA(e,t,n){let r=PA[t];if(r===void 0)return!0;let i=n,a=!1;if(i=zA(e,i),e[i]===`[`){if(!r.modelBracket)return!1;let t=e.indexOf(`]`,i+1);if(t===-1)return!1;let n=e.slice(i+1,t).trim();a=FA.test(n),i=t+1}for(let t=0;t<r.colorArgs;t+=1){if(i=zA(e,i),e[i]!==`{`)return!1;let t=BA(e,i+1);if(t===-1)return!1;let n=e.slice(i+1,t);if(!a&&!RA(n))return!1;i=t+1}return!0}function RA(e){return e.trim()!==``&&IA.test(e)}function zA(e,t){let n=t;for(;n<e.length&&/\s/u.test(e[n]??``);)n+=1;return n}function BA(e,t){let n=0;for(let r=t;r<e.length;r+=1)if(e[r]===`{`)n+=1;else if(e[r]===`}`){if(n===0)return r;--n}return-1}function VA(e){return e.displayMode?`<p>${Wk(e.raw)}</p>`:Wk(e.raw)}var HA=class extends Error{constructor(){super(`MathJax has not finished loading yet`),this.name=`MathJaxNotReadyError`}},UA,WA,GA,KA;function qA(){return UA??=NS(()=>import(`./mathjaxEngine-CBUWmGvi.js`).then(e=>{GA=e.mathJaxStyles(),KA=JA(GA);let t=document.createElement(`style`);return t.setAttribute(`data-mathjax-chtml`,``),t.textContent=GA,document.head.append(t),WA=e,e}),[],import.meta.url).catch(e=>{throw console.error(`MathJax failed to load; math will render as literal source.`,e),e}),UA}function JA(e){if(!(typeof CSSStyleSheet!=`function`||typeof CSSStyleSheet.prototype.replaceSync!=`function`))try{let t=new CSSStyleSheet;return t.replaceSync(e),t}catch{return}}function YA(e){if(GA===void 0)return;if(KA!==void 0&&`adoptedStyleSheets`in e){e.adoptedStyleSheets.includes(KA)||(e.adoptedStyleSheets=[...e.adoptedStyleSheets,KA]);return}if(e.querySelector(`style[data-mathjax-chtml]`)!==null)return;let t=document.createElement(`style`);t.setAttribute(`data-mathjax-chtml`,``),t.textContent=GA,e.append(t)}function XA(){return WA!==void 0}function ZA(){return qA().then(()=>void 0)}function QA(e,t){if(WA===void 0)throw new HA;return WA.convertLatex(e,t.displayMode)}var $A=new V.Renderer;$A.html=({text:e})=>Wk(e);var ej=1600,tj=6e6,nj=8,rj=new Map,ij=0,aj=QA;function oj(e,t={}){let n=qk(e),r=t.cache!==!1&&t.renderMath===void 0&&(!n||XA());if(r){let t=rj.get(e);if(t!==void 0)return rj.delete(e),rj.set(e,t),t.html}let i=lj(t.renderMath!==void 0||qk(e)?Jk(e,t.renderMath??aj):V.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:$A}));return r&&sj(e,i),i}function sj(e,t){let n=e.length+t.length;if(n>tj/nj)return;let r=rj.get(e);r!==void 0&&(rj.delete(e),ij-=r.chars),rj.set(e,{html:t,chars:n}),ij+=n,cj()}function cj(){for(;rj.size>1&&(rj.size>ej||ij>tj);){let e=rj.entries().next();if(e.done===!0)break;let[t,n]=e.value;rj.delete(t),ij-=n.chars}}function lj(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`)&&!uj(t.value)&&e.removeAttribute(t.name)}if(e instanceof HTMLElement){let t=e.style.position.trim().toLowerCase();(t===`fixed`||t===`absolute`||t===`sticky`)&&e.removeAttribute(`style`)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),t.innerHTML}function uj(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}function dj({text:e,live:t}){return t&&(e.length>=24e3||Kk(e))}var fj=class extends y{constructor(...e){super(...e),this.text=``,this.live=!1,this.retryMathRender=!1,this.mathRetryScheduled=!1,this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`.code-copy-button`);if(!(t instanceof HTMLButtonElement))return;let n=t.closest(`.code-block-wrapper`);if(!(n instanceof HTMLElement))return;let r=n.querySelector(`pre code`);r instanceof HTMLElement&&this.copyCode(r.textContent,t)}}render(){return dj(this)?g`<div class="formatted plain" dir="auto">${this.text}</div>`:g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${Fk(this.renderMarkdown())}</div>`}renderMarkdown(){return this.retryMathRender?(this.retryMathRender=!1,oj(this.text,{cache:!1,renderMath:QA})):oj(this.text,{cache:!this.live})}scheduleMathRetry(){this.mathRetryScheduled||XA()||this.live||!Kk(this.text)||(this.mathRetryScheduled=!0,ZA().then(()=>{this.retryMathRender=!0,this.requestUpdate()}).catch(()=>{}))}updated(){this.enhanceCodeBlocks(),Kk(this.text)&&this.renderRoot instanceof ShadowRoot&&YA(this.renderRoot),this.scheduleMathRetry()}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 zO(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=[TS,h`
|
|
2874
|
+
`)}}if(rA(i)||(a.push(i),s+=i.length+ +(a.length>1),s>Ik)||t<0)return;o=t+1}}function eA(e){let t=/^( {0,3})(\$\$|\\\[)([ \t]*)$/u.exec(e);if(t!==null){let e=t[2];return e!==`$$`&&e!==`\\[`?void 0:{delimiter:e,delimiterEnd:t[0].length}}let n=/^( {0,3})(\$\$|\\\[)/u.exec(e);if(n===null)return;let r=n[2];if(!(r!==`$$`&&r!==`\\[`))return{delimiter:r,delimiterEnd:n[0].length}}function tA(e,t){return RegExp(`^ {0,3}${t===`$$`?`\\$\\$`:`\\\\\\]`}[ \\t]*$`,`u`).test(e)}function nA(e,t){let n=t===`$$`?`$$`:`\\]`,r=e.slice(0,Ik+n.length),i=0;for(;i<r.length;){let t=r.indexOf(n,i);if(t<0||t>Ik)return-1;if(/^[ \t]*$/u.test(e.slice(t+n.length)))return t;i=t+n.length}return-1}function rA(e){return/^ {0,3}(?:```|~~~)/u.test(e)}function iA(e){return aA(e),e}function aA(e){for(let t of e)oA(t)}function oA(e){if(lA(e,`paragraph`)||lA(e,`heading`)){e.tokens=cA(e.tokens);return}if(lA(e,`blockquote`)){aA(e.tokens);return}if(lA(e,`list`)){for(let t of e.items)aA(t.tokens);return}if(lA(e,`list_item`)){sA(e.tokens);return}if(lA(e,`text`)&&e.tokens!==void 0){e.tokens=cA(e.tokens);return}if(lA(e,`table`)){for(let t of e.header)t.tokens=cA(t.tokens);for(let t of e.rows)for(let e of t)e.tokens=cA(e.tokens)}}function sA(e){for(let t of e)lA(t,`text`)&&t.tokens!==void 0?t.tokens=cA(t.tokens):oA(t)}function cA(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===void 0)break;if(uA(r)){let r=[];for(;n<e.length;){let t=e[n];if(t===void 0||!uA(t))break;r.push(t),n+=1}t.push(...dA(r));continue}(lA(r,`em`)||lA(r,`strong`)||lA(r,`del`)||lA(r,`text`)&&r.tokens!==void 0)&&(r.tokens=cA(r.tokens)),t.push(r),n+=1}return t}function lA(e,t){return e.type===t}function uA(e){return lA(e,`escape`)||lA(e,`text`)&&e.tokens===void 0}function dA(e){let t=e.map(e=>e.raw).join(``);if(!qk(t))return e;let n=mA(t);if(n.length===0)return e;let r=fA(e),i={index:0},a=[],o=0;for(let e of n){pA(a,r,i,o,e.start);let n=t.slice(e.start,e.end);e.kind===`math`?a.push({type:e.displayMode===!0?`latex-display`:`latex-inline`,raw:n,tex:e.tex??``,displayMode:e.displayMode===!0}):a.push({type:`latex-inline-literal`,raw:n}),o=e.end}return pA(a,r,i,o,t.length),a}function fA(e){let t=[],n=0;for(let r of e){let e=n+r.raw.length;t.push({token:r,start:n,end:e}),n=e}return t}function pA(e,t,n,r,i){if(!(r>=i)){for(;n.index<t.length;){let e=t[n.index];if(e===void 0||e.end>r)break;n.index+=1}for(;n.index<t.length;n.index+=1){let a=t[n.index];if(a===void 0||a.start>=i)break;let o=Math.max(r,a.start)-a.start,s=Math.min(i,a.end)-a.start;if(o===0&&s===a.token.raw.length)e.push(a.token);else{let t=a.token.raw.slice(o,s),n=a.token.text.slice(o,s);e.push({type:`text`,raw:t,text:n.length===t.length?n:t,escaped:a.token.type===`text`&&a.token.escaped})}if(a.end>i)break}}}function mA(e){let t={head:void 0,tail:void 0},n=0,r,i,a,o,s=!1,c=!1;for(let l=0;l<e.length;l+=1){r=vA(r),i=vA(i),a=vA(a),o=vA(o),r!==void 0&&l-r.start-1>Ik&&(gA(t,r.placeholder),r=void 0,s=!0),i!==void 0&&l-i.start-2>Ik&&(gA(t,i.placeholder),i=void 0,c=!0),a!==void 0&&l-a.start-2>Ik&&(a=void 0),o!==void 0&&l-o.start-2>Ik&&(o=void 0);let u=e[l];if(u===`\\`){if(n+=1,n%2==1){let n=e[l+1];if(n===`(`||n===`)`||n===`[`||n===`]`){let r=hA(t,l,l+2,`literal`);if(n===`(`)a??={start:l,placeholder:r};else if(n===`)`&&a!==void 0){let n=e.slice(a.start+2,l);n.length<=Ik&&n.length>0&&n.trim()!==``&&!/\s/u.test(n[0]??``)&&!/\s/u.test(n.at(-1)??``)&&SA(e,a.start)&&CA(e,l+2)&&_A(t,a.placeholder,l+2,`math`,n,!1),a=void 0}else if(n===`[`)o??={start:l,placeholder:r};else if(n===`]`&&o!==void 0){let n=e.slice(o.start+2,l);n.length<=Ik&&n.length>0&&n.trim()!==``&&_A(t,o.placeholder,l+2,`literal`),o=void 0}}}continue}if(u===`$`){let a=n%2==1;if(e[l+1]===`$`){if(!a){if(i===void 0&&!c)i={start:l,placeholder:hA(t,l,l+2,`literal`)};else if(i!==void 0){let n=e.slice(i.start+2,l);n.length<=Ik&&n.trim()!==``?_A(t,i.placeholder,l+2,`literal`):(gA(t,i.placeholder),n.length>Ik&&(c=!0)),i=void 0}}l+=1,n=0;continue}if(!a&&!s)if(r===void 0)bA(e,l)&&(r={start:l,placeholder:hA(t,l,l+1,`literal`)});else{let n=e.slice(r.start+1,l);xA(e,r.start,l,n)?(_A(t,r.placeholder,l+1,`math`,n,!1),r=void 0):(gA(t,r.placeholder),r=void 0,bA(e,l)&&(r={start:l,placeholder:hA(t,l,l+1,`literal`)}))}n=0;continue}n=0}return r!==void 0&&gA(t,r.placeholder),i!==void 0&&gA(t,i.placeholder),EA(yA(t))}function hA(e,t,n,r){let i={start:t,end:n,kind:r,linked:!0,previous:e.tail,next:void 0};return e.tail===void 0?e.head=i:e.tail.next=i,e.tail=i,i}function gA(e,t){t.linked&&=(t.previous===void 0?e.head=t.next:t.previous.next=t.next,t.next===void 0?e.tail=t.previous:t.next.previous=t.previous,t.previous=void 0,t.next=void 0,!1)}function _A(e,t,n,r,i,a){let o=t.next;for(;o!==void 0&&o.start<n;){let t=o.next;gA(e,o),o=t}t.end=n,t.kind=r,i===void 0?delete t.tex:t.tex=i,a===void 0?delete t.displayMode:t.displayMode=a}function vA(e){return e?.placeholder.linked===!0?e:void 0}function yA(e){let t=[];for(let n=e.head;n!==void 0;n=n.next){let e={start:n.start,end:n.end,kind:n.kind};n.tex!==void 0&&(e.tex=n.tex),n.displayMode!==void 0&&(e.displayMode=n.displayMode),t.push(e)}return t}function bA(e,t){let n=e[t+1];return SA(e,t)&&n!==void 0&&!/\s/u.test(n)}function xA(e,t,n,r){return n>t+1&&r.length>0&&!/\s/u.test(r.at(-1)??``)&&CA(e,n+1)}function SA(e,t){if(t<=0)return!0;let n=t-1,r=TA(e.charCodeAt(n))?n-1:n;return wA(e.codePointAt(r))}function CA(e,t){return wA(e.codePointAt(t))}function wA(e){return e===void 0||/[\s\p{P}\p{S}]/u.test(String.fromCodePoint(e))}function TA(e){return e>=56320&&e<=57343}function EA(e){let t=[];for(let n of e){let e=t.at(-1);e?.kind===`literal`&&n.kind===`literal`&&e.end===n.start?e.end=n.end:t.push({...n})}return t}function DA(e,t,n){if(e.type===`latex-inline-literal`)return Wk(e.raw);if(e.type===`latex-block-literal`)return`<p>${Wk(e.raw)}</p>`;let r=OA(e);if(r===void 0)return``;if(!kA(r.tex,t))return VA(r);let i;try{i=n(r.tex,{displayMode:r.displayMode})}catch{return VA(r)}if(!AA(i,t))return VA(r);let a=`aria-label="${Gk(r.tex)}"`;return r.displayMode?`<div class="math-display" role="img" ${a}>${i}</div>`:`<span class="math-inline" role="img" ${a}>${i}</span>`}function OA(e){if(e.type!==`latex-inline`&&e.type!==`latex-display`)return;let t=e,n=t.tex,r=t.displayMode;if(!(typeof n!=`string`||typeof r!=`boolean`))return{type:e.type,raw:e.raw,tex:n,displayMode:r}}function kA(e,t){return t.outputAdmissionClosed||e.length>Lk||t.mathSourceUnits+e.length>Rk||!jA(e)?!1:(t.mathSourceUnits+=e.length,!0)}function AA(e,t){return e.length>Uk||t.mathOutputUnits+e.length>Hk?(t.outputAdmissionClosed=!0,!1):(t.mathOutputUnits+=e.length,!0)}function jA(e){let t=0,n=0,r=0;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`\\`){let t=i;for(;t<e.length&&e[t]===`\\`;)t+=1;let a=t-i;if(a>=2&&(r+=Math.floor(a/2)),r>Vk)return!1;if(a%2==1){let r=e[t];if(/[A-Za-z@]/u.test(r??``)){n+=1;let r=MA(e,t),a=e.slice(t-1,r);if(NA(a)||!LA(e,a,r))return!1;i=r-1}else i=t}else i=t-1;continue}if(a===`{`){if(t+=1,t>zk)return!1}else if(a===`}`)t=Math.max(0,t-1);else if(a===`&`&&(r+=1,r>Vk))return!1}return n<=Bk}function MA(e,t){let n=t;for(;n<e.length&&/[A-Za-z@]/u.test(e[n]??``);)n+=1;return n}function NA(e){return[`\\def`,`\\gdef`,`\\edef`,`\\xdef`,`\\let`,`\\newcommand`,`\\renewcommand`,`\\href`,`\\url`,`\\style`,`\\class`,`\\cssId`,`\\bbox`,`\\unicode`,`\\definecolor`].includes(e)}var PA={"\\color":{modelBracket:!0,colorArgs:1},"\\textcolor":{modelBracket:!0,colorArgs:1},"\\colorbox":{modelBracket:!1,colorArgs:1},"\\fcolorbox":{modelBracket:!1,colorArgs:2},"\\rowcolor":{modelBracket:!0,colorArgs:1},"\\cellcolor":{modelBracket:!0,colorArgs:1},"\\columncolor":{modelBracket:!0,colorArgs:1}},FA=/^(?:rgb|RGB|gray)$/u,IA=/^[A-Za-z0-9#%(),.!\s-]+$/u;function LA(e,t,n){let r=PA[t];if(r===void 0)return!0;let i=n,a=!1;if(i=zA(e,i),e[i]===`[`){if(!r.modelBracket)return!1;let t=e.indexOf(`]`,i+1);if(t===-1)return!1;let n=e.slice(i+1,t).trim();a=FA.test(n),i=t+1}for(let t=0;t<r.colorArgs;t+=1){if(i=zA(e,i),e[i]!==`{`)return!1;let t=BA(e,i+1);if(t===-1)return!1;let n=e.slice(i+1,t);if(!a&&!RA(n))return!1;i=t+1}return!0}function RA(e){return e.trim()!==``&&IA.test(e)}function zA(e,t){let n=t;for(;n<e.length&&/\s/u.test(e[n]??``);)n+=1;return n}function BA(e,t){let n=0;for(let r=t;r<e.length;r+=1)if(e[r]===`{`)n+=1;else if(e[r]===`}`){if(n===0)return r;--n}return-1}function VA(e){return e.displayMode?`<p>${Wk(e.raw)}</p>`:Wk(e.raw)}var HA=class extends Error{constructor(){super(`MathJax has not finished loading yet`),this.name=`MathJaxNotReadyError`}},UA,WA,GA,KA;function qA(){return UA??=NS(()=>import(`./mathjaxEngine-WPWR2qyM.js`).then(e=>{GA=e.mathJaxStyles(),KA=JA(GA);let t=document.createElement(`style`);return t.setAttribute(`data-mathjax-chtml`,``),t.textContent=GA,document.head.append(t),WA=e,e}),[],import.meta.url).catch(e=>{throw console.error(`MathJax failed to load; math will render as literal source.`,e),e}),UA}function JA(e){if(!(typeof CSSStyleSheet!=`function`||typeof CSSStyleSheet.prototype.replaceSync!=`function`))try{let t=new CSSStyleSheet;return t.replaceSync(e),t}catch{return}}function YA(e){if(GA===void 0)return;if(KA!==void 0&&`adoptedStyleSheets`in e){e.adoptedStyleSheets.includes(KA)||(e.adoptedStyleSheets=[...e.adoptedStyleSheets,KA]);return}if(e.querySelector(`style[data-mathjax-chtml]`)!==null)return;let t=document.createElement(`style`);t.setAttribute(`data-mathjax-chtml`,``),t.textContent=GA,e.append(t)}function XA(){return WA!==void 0}function ZA(){return qA().then(()=>void 0)}function QA(e,t){if(WA===void 0)throw new HA;return WA.convertLatex(e,t.displayMode)}var $A=new V.Renderer;$A.html=({text:e})=>Wk(e);var ej=1600,tj=6e6,nj=8,rj=new Map,ij=0,aj=QA;function oj(e,t={}){let n=qk(e),r=t.cache!==!1&&t.renderMath===void 0&&(!n||XA());if(r){let t=rj.get(e);if(t!==void 0)return rj.delete(e),rj.set(e,t),t.html}let i=lj(t.renderMath!==void 0||qk(e)?Jk(e,t.renderMath??aj):V.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:$A}));return r&&sj(e,i),i}function sj(e,t){let n=e.length+t.length;if(n>tj/nj)return;let r=rj.get(e);r!==void 0&&(rj.delete(e),ij-=r.chars),rj.set(e,{html:t,chars:n}),ij+=n,cj()}function cj(){for(;rj.size>1&&(rj.size>ej||ij>tj);){let e=rj.entries().next();if(e.done===!0)break;let[t,n]=e.value;rj.delete(t),ij-=n.chars}}function lj(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`)&&!uj(t.value)&&e.removeAttribute(t.name)}if(e instanceof HTMLElement){let t=e.style.position.trim().toLowerCase();(t===`fixed`||t===`absolute`||t===`sticky`)&&e.removeAttribute(`style`)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),t.innerHTML}function uj(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}function dj({text:e,live:t}){return t&&(e.length>=24e3||Kk(e))}var fj=class extends y{constructor(...e){super(...e),this.text=``,this.live=!1,this.retryMathRender=!1,this.mathRetryScheduled=!1,this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`.code-copy-button`);if(!(t instanceof HTMLButtonElement))return;let n=t.closest(`.code-block-wrapper`);if(!(n instanceof HTMLElement))return;let r=n.querySelector(`pre code`);r instanceof HTMLElement&&this.copyCode(r.textContent,t)}}render(){return dj(this)?g`<div class="formatted plain" dir="auto">${this.text}</div>`:g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${Fk(this.renderMarkdown())}</div>`}renderMarkdown(){return this.retryMathRender?(this.retryMathRender=!1,oj(this.text,{cache:!1,renderMath:QA})):oj(this.text,{cache:!this.live})}scheduleMathRetry(){this.mathRetryScheduled||XA()||this.live||!Kk(this.text)||(this.mathRetryScheduled=!0,ZA().then(()=>{this.retryMathRender=!0,this.requestUpdate()}).catch(()=>{}))}updated(){this.enhanceCodeBlocks(),Kk(this.text)&&this.renderRoot instanceof ShadowRoot&&YA(this.renderRoot),this.scheduleMathRetry()}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 zO(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=[TS,h`
|
|
2875
2875
|
.formatted.plain { white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
|
|
2876
2876
|
.math-inline { display: inline-block; max-width: 100%; overflow-x: auto; vertical-align: -0.25em; }
|
|
2877
2877
|
.math-display { display: block; max-width: 100%; overflow-x: auto; margin: 10px 0; }
|
|
@@ -6726,6 +6726,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6726
6726
|
title=${DV(e)}
|
|
6727
6727
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
6728
6728
|
aria-expanded=${String(this.open)}
|
|
6729
|
+
aria-describedby="machine-status-description"
|
|
6729
6730
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
6730
6731
|
@keydown=${e=>{this.handleSwitcherButtonKeydown(e)}}
|
|
6731
6732
|
>
|
|
@@ -6734,9 +6735,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6734
6735
|
<span class="machine-switcher-kicker">Machine</span>
|
|
6735
6736
|
<span class="machine-switcher-label">${n}</span>
|
|
6736
6737
|
</span>
|
|
6737
|
-
<span class=${`machine-status ${t}`}>${EV(t)}</span>
|
|
6738
|
+
<span class=${`machine-status ${t}`} title=${EV(t)}>${EV(t)}</span>
|
|
6738
6739
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
6739
6740
|
</button>
|
|
6741
|
+
<span id="machine-status-description">Machine status: ${EV(t)}.</span>
|
|
6740
6742
|
${this.open?g`
|
|
6741
6743
|
<div class="machine-switcher-menu" style=${this.menuStyle} @click=${e=>{e.stopPropagation()}}>
|
|
6742
6744
|
${this.machines.map(e=>this.renderMachineOption(e))}
|
|
@@ -6774,17 +6776,28 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6774
6776
|
</div>
|
|
6775
6777
|
`:null}
|
|
6776
6778
|
</div>
|
|
6777
|
-
`}renderActivity(e){let t=TV(e,this.statuses);if(t===`offline`||t===`error`)return;let n=zf(this.activities[e.id]);return QT(n,n===`terminal`?`Machine terminal active`:`Machine active`)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`Machine: ${e.name}. Switch machine.`}switcherButton(){return this.renderRoot.querySelector(`.machine-switcher-button`)}handleSwitcherButtonKeydown(e){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key===`Escape`&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key===`ArrowUp`){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key===`ArrowDown`){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key===`Home`){this.focusIndexedMachineOption(0,e);return}if(e.key===`End`){this.focusIndexedMachineOption(-1,e);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key===`ArrowLeft`||e.key===`Escape`)&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()})
|
|
6778
|
-
:host { min-width: 0; display: block; }
|
|
6779
|
+
`}renderActivity(e){let t=TV(e,this.statuses);if(t===`offline`||t===`error`)return;let n=zf(this.activities[e.id]);return QT(n,n===`terminal`?`Machine terminal active`:`Machine active`)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`Machine: ${e.name}. Switch machine.`}switcherButton(){return this.renderRoot.querySelector(`.machine-switcher-button`)}handleSwitcherButtonKeydown(e){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.closeMenuWithoutFocus(),this.onFocusNextSection();return}if((e.key===`Escape`||e.key===`ArrowLeft`)&&this.open){e.preventDefault(),e.stopPropagation(),this.closeMenuAndFocusSwitcherButton();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.closeMenuAndFocusSwitcherButton())}closeMenuWithoutFocus(){this.open=!1,this.openActionsMachineId=void 0}closeMenuAndFocusSwitcherButton(){this.closeMenuWithoutFocus(),this.updateComplete.then(()=>{this.focusSwitcherButton()})}toggleMenu(e){this.menuStyle=OV(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=OV(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=JT(t,{constrainTo:`viewport`}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}static{this.styles=h`
|
|
6780
|
+
:host { min-width: 0; display: block; container-type: inline-size; container-name: machine-switcher; }
|
|
6779
6781
|
.machine-switcher { min-width: 0; }
|
|
6780
6782
|
.machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
|
|
6781
6783
|
.machine-switcher-button:hover, .machine-switcher-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
|
|
6782
|
-
.machine-switcher-text { flex: 1 1 auto; min-width:
|
|
6783
|
-
.machine-switcher-kicker { color: var(--pi-muted); font-size: 10px; line-height: 1; text-transform: uppercase; letter-spacing: .02em; }
|
|
6784
|
+
.machine-switcher-text { flex: 1 1 auto; min-width: 48px; display: grid; gap: 1px; }
|
|
6785
|
+
.machine-switcher-kicker { white-space: nowrap; color: var(--pi-muted); font-size: 10px; line-height: 1; text-transform: uppercase; letter-spacing: .02em; }
|
|
6784
6786
|
.machine-switcher-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 600; line-height: 1.2; }
|
|
6785
6787
|
.machine-status { flex: 0 0 auto; color: var(--pi-muted); font-size: 11px; }
|
|
6786
6788
|
.machine-status.online { color: var(--pi-success); }
|
|
6787
6789
|
.machine-status.offline, .machine-status.error { color: var(--pi-danger); }
|
|
6790
|
+
#machine-status-description {
|
|
6791
|
+
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
|
6792
|
+
overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%);
|
|
6793
|
+
white-space: nowrap; border: 0;
|
|
6794
|
+
}
|
|
6795
|
+
@container machine-switcher (width < 150px) {
|
|
6796
|
+
.machine-switcher-button > .machine-status {
|
|
6797
|
+
font-size: 0; width: 7px; height: 7px; border-radius: 50%;
|
|
6798
|
+
background: currentColor; overflow: hidden; flex: 0 0 auto;
|
|
6799
|
+
}
|
|
6800
|
+
}
|
|
6788
6801
|
.machine-chevron { flex: 0 0 auto; color: var(--pi-muted); font-size: 11px; }
|
|
6789
6802
|
.activity-indicator { flex: 0 0 auto; display: inline-block; width: 7px; height: 7px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; }
|
|
6790
6803
|
.activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
|
|
@@ -6807,7 +6820,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6807
6820
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
6808
6821
|
.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); }
|
|
6809
6822
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
6810
|
-
`}};H([x({attribute:!1})],wV.prototype,`machines`,void 0),H([x({attribute:!1})],wV.prototype,`selected`,void 0),H([x({attribute:!1})],wV.prototype,`statuses`,void 0),H([x({attribute:!1})],wV.prototype,`activities`,void 0),H([x({attribute:!1})],wV.prototype,`onSelect`,void 0),H([x({attribute:!1})],wV.prototype,`onRemove`,void 0),H([x({attribute:!1})],wV.prototype,`onFocusNextSection`,void 0),H([x({attribute:!1})],wV.prototype,`onCancelKeyboardNavigation`,void 0),H([S()],wV.prototype,`open`,void 0),H([S()],wV.prototype,`menuStyle`,void 0),H([S()],wV.prototype,`openActionsMachineId`,void 0),H([S()],wV.prototype,`actionMenuStyle`,void 0),wV=H([b(`machine-switcher`)],wV);function TV(e,t){return t[e.id]?.status??e.status??`unknown`}function EV(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function DV(e){return e.baseUrl
|
|
6823
|
+
`}};H([x({attribute:!1})],wV.prototype,`machines`,void 0),H([x({attribute:!1})],wV.prototype,`selected`,void 0),H([x({attribute:!1})],wV.prototype,`statuses`,void 0),H([x({attribute:!1})],wV.prototype,`activities`,void 0),H([x({attribute:!1})],wV.prototype,`onSelect`,void 0),H([x({attribute:!1})],wV.prototype,`onRemove`,void 0),H([x({attribute:!1})],wV.prototype,`onFocusNextSection`,void 0),H([x({attribute:!1})],wV.prototype,`onCancelKeyboardNavigation`,void 0),H([S()],wV.prototype,`open`,void 0),H([S()],wV.prototype,`menuStyle`,void 0),H([S()],wV.prototype,`openActionsMachineId`,void 0),H([S()],wV.prototype,`actionMenuStyle`,void 0),wV=H([b(`machine-switcher`)],wV);function TV(e,t){return t[e.id]?.status??e.status??`unknown`}function EV(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function DV(e){return e.baseUrl===void 0?e.name:`${e.name} — ${e.baseUrl}`}function OV(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: ${kV(t.bottom)};`,`left: ${kV(r)};`,`width: ${kV(n)};`,`max-height: ${kV(i)};`].join(` `)}function kV(e){return`${String(Math.round(e))}px`}var AV=[{id:`models`,label:`Models`},{id:`skills`,label:`Skills`},{id:`plugins`,label:`Plugins`}],Q=class extends y{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.projectSessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canReorderSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`Update and restart Pi-Web on this machine to delete archived sessions.`,this.cleanupUnavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.skillsEnabled=!1,this.pluginsEnabled=!1,this.projectStatisticsAvailable=!1}async focusSection(e){switch(await this.updateComplete,e){case`machines`:return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case`projects`:return await this.focusNavigableSection(this.projectList);case`workspaces`:return await this.focusNavigableSection(this.workspaceList);case`sessions`:return await this.focusNavigableSection(this.sessionList)}}render(){let e=this.version;return g`
|
|
6811
6824
|
<header>
|
|
6812
6825
|
<strong class="brand" aria-label=${e===void 0?`Pi WebUI`:`Pi WebUI version ${e}`}><span class="brand-symbol" aria-hidden="true">π</span><span>WebUI</span>${e===void 0?null:g`<span class="brand-version">v${e}</span>`}</strong>
|
|
6813
6826
|
${PV(this.machines)?g`
|
|
@@ -6823,7 +6836,6 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6823
6836
|
></machine-switcher>
|
|
6824
6837
|
`:null}
|
|
6825
6838
|
<div class="header-actions">
|
|
6826
|
-
${this.refreshControl}
|
|
6827
6839
|
<button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
|
|
6828
6840
|
</div>
|
|
6829
6841
|
</header>
|
|
@@ -6927,13 +6939,14 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6927
6939
|
${AV.map(e=>jV(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
|
|
6928
6940
|
</footer>
|
|
6929
6941
|
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=FV(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(IV(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
|
|
6930
|
-
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
6942
|
+
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; container-type: inline-size; container-name: navigation-header; }
|
|
6931
6943
|
:host([compact]) { flex: 1 1 auto; }
|
|
6932
6944
|
header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
6933
6945
|
header strong { flex: 0 0 auto; }
|
|
6934
6946
|
.brand { display: inline-flex; align-items: center; gap: 5px; }
|
|
6935
6947
|
.brand-symbol { font-size: 28px; font-weight: 700; line-height: 1; }
|
|
6936
6948
|
.brand-version { color: var(--pi-muted); font-size: 12px; font-weight: 500; line-height: 1; }
|
|
6949
|
+
@container navigation-header (inline-size < 372px) { .brand-version { display: none; } }
|
|
6937
6950
|
machine-switcher { flex: 1 1 auto; min-width: 0; }
|
|
6938
6951
|
:host([compact]) header { display: none; }
|
|
6939
6952
|
.header-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; }
|
|
@@ -7049,7 +7062,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7049
7062
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
7050
7063
|
.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; }
|
|
7051
7064
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
7052
|
-
`}};H([x({attribute:!1})],HV.prototype,`onReload`,void 0),HV=H([b(`app-refresh-control`)],HV);var UV=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],WV=`file-manager`,GV=`browser`,KV=[...UV],qV=new Set(UV),JV=`pi-webui:activity-rail-order`;function YV(){return typeof localStorage>`u`?void 0:localStorage}function XV(e){return qV.has(e)}function ZV(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===WV?`git-update-manager`:r;if(e!==GV){if(!XV(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===UV.length)return t;let r=[...t];if(!n.has(`git-update-manager`)){let e=r.indexOf(`terminal`);r.splice(e+1,0,`git-update-manager`)}return n.has(`info`)||r.push(`info`),r.length===UV.length?r:void 0}function QV(){try{let e=YV();if(e===void 0)return;let t=e.getItem(JV);return t===null?void 0:ZV(JSON.parse(t))}catch{return}}function $V(e){try{let t=YV();if(t===void 0)return;t.setItem(JV,JSON.stringify(e))}catch{}}var eH=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function tH(e){return eH.includes(e)}function nH(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}var rH=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...KV],this.pluginItems=[],this.compactOpen=!1,this.onDesktopMediaChange=e=>{e.matches&&this.compactOpen&&this.onCloseCompact?.(),this.requestUpdate()},this.openTerminal=()=>{this.invokeCoreAction(this.onOpenTerminal)},this.openGitUpdateManager=()=>{this.invokeCoreAction(this.onOpenGitUpdateManager)},this.openTheme=()=>{this.invokeCoreAction(this.onOpenTheme)},this.openSystemPrompt=()=>{this.invokeCoreAction(this.onOpenSystemPrompt)},this.openHistory=()=>{this.invokeCoreAction(this.onOpenHistory)},this.openInfo=()=>{this.invokeCoreAction(this.onOpenInfo)},this.openSettings=()=>{this.invokeCoreAction(this.onOpenSettings)},this.openPluginActivity=(e,t)=>{this.closeCompactBeforeAction(),nH(t)&&this.onOpenPluginActivity?.(e,t)},this.closeCompact=()=>{this.onCloseCompact?.()},this.handleCompactBackdropMouseDown=e=>{e.target===e.currentTarget&&(e.preventDefault(),this.closeCompact())},this.handleCompactKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeCompact())},this.onDragStart=(e,t)=>{this.dragItem=e,t.dataTransfer!==null&&(t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,e)),requestAnimationFrame(()=>{this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.add(`dragging`)})},this.onDragEnd=e=>{this.dragItem=void 0,this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.remove(`dragging`),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)})},this.onRailDragOver=e=>{if(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`move`),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),t!==null&&t.dataset.railItem!==this.dragItem&&t.classList.add(`drag-over`)},this.onRailDrop=e=>{if(e.preventDefault(),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);if(t===null||t.dataset.railItem===this.dragItem){this.dragItem=void 0;return}let n=t.dataset.railItem;if(n===void 0||!tH(n)){this.dragItem=void 0;return}let r=[...this.railOrder],i=r.indexOf(this.dragItem),a=r.indexOf(n);if(i===-1||a===-1){this.dragItem=void 0;return}r.splice(i,1),r.splice(a,0,this.dragItem),this.railOrder=r,this.onRailOrderChange?.(r),this.dragItem=void 0},typeof window<`u`&&`matchMedia`in window&&(this.desktopMedia=window.matchMedia(cw))}connectedCallback(){super.connectedCallback(),this.desktopMedia?.addEventListener(`change`,this.onDesktopMediaChange)}disconnectedCallback(){super.disconnectedCallback(),this.desktopMedia?.removeEventListener(`change`,this.onDesktopMediaChange)}updated(e){!e.has(`compactOpen`)||!this.compactOpen||this.isDesktopRailLayout()||this.renderRoot.querySelector(`.compact-rail-close`)?.focus()}isDesktopRailLayout(){return this.desktopMedia?.matches??!0}closeCompactBeforeAction(){this.isDesktopRailLayout()||this.onCloseCompact?.()}invokeCoreAction(e){this.closeCompactBeforeAction(),e?.()}resolveDragTarget(e){if(e===null||!(e instanceof HTMLElement))return null;let t=e.closest(`[data-rail-item]`);return t instanceof HTMLElement?t:null}dndProps(e){return{draggable:`true`,"data-rail-item":e}}renderReorderableButton(e){switch(e){case`terminal`:return this.renderTerminalButton();case`git-update-manager`:return this.renderGitUpdateManagerButton();case`theme`:return this.renderThemeButton();case`system-prompt`:return this.renderSystemPromptButton();case`history`:return this.renderHistoryButton();case`info`:return this.renderInfoButton()}}renderTerminalButton(){let e=this.dndProps(`terminal`),t=this.terminalCount>0?this.terminalCount:void 0,n=t===void 0?``:`${String(t)} active terminal${t===1?``:`s`}`;return g`
|
|
7065
|
+
`}};H([x({attribute:!1})],HV.prototype,`onReload`,void 0),HV=H([b(`app-refresh-control`)],HV);var UV=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],WV=`file-manager`,GV=`browser`,KV=[...UV],qV=new Set(UV),JV=`pi-webui:activity-rail-order`;function YV(){return typeof localStorage>`u`?void 0:localStorage}function XV(e){return qV.has(e)}function ZV(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===WV?`git-update-manager`:r;if(e!==GV){if(!XV(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===UV.length)return t;let r=[...t];if(!n.has(`git-update-manager`)){let e=r.indexOf(`terminal`);r.splice(e+1,0,`git-update-manager`)}return n.has(`info`)||r.push(`info`),r.length===UV.length?r:void 0}function QV(){try{let e=YV();if(e===void 0)return;let t=e.getItem(JV);return t===null?void 0:ZV(JSON.parse(t))}catch{return}}function $V(e){try{let t=YV();if(t===void 0)return;t.setItem(JV,JSON.stringify(e))}catch{}}var eH=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function tH(e){return eH.includes(e)}function nH(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}var rH=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...KV],this.pluginItems=[],this.compactOpen=!1,this.showReload=!1,this.onDesktopMediaChange=e=>{e.matches&&this.compactOpen&&this.onCloseCompact?.(),this.requestUpdate()},this.openTerminal=()=>{this.invokeCoreAction(this.onOpenTerminal)},this.openGitUpdateManager=()=>{this.invokeCoreAction(this.onOpenGitUpdateManager)},this.openTheme=()=>{this.invokeCoreAction(this.onOpenTheme)},this.openSystemPrompt=()=>{this.invokeCoreAction(this.onOpenSystemPrompt)},this.openHistory=()=>{this.invokeCoreAction(this.onOpenHistory)},this.openInfo=()=>{this.invokeCoreAction(this.onOpenInfo)},this.openSettings=()=>{this.invokeCoreAction(this.onOpenSettings)},this.reloadApp=()=>{this.invokeCoreAction(this.onReload)},this.openPluginActivity=(e,t)=>{this.closeCompactBeforeAction(),nH(t)&&this.onOpenPluginActivity?.(e,t)},this.closeCompact=()=>{this.onCloseCompact?.()},this.handleCompactBackdropMouseDown=e=>{e.target===e.currentTarget&&(e.preventDefault(),this.closeCompact())},this.handleCompactKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeCompact())},this.onDragStart=(e,t)=>{this.dragItem=e,t.dataTransfer!==null&&(t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,e)),requestAnimationFrame(()=>{this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.add(`dragging`)})},this.onDragEnd=e=>{this.dragItem=void 0,this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.remove(`dragging`),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)})},this.onRailDragOver=e=>{if(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`move`),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),t!==null&&t.dataset.railItem!==this.dragItem&&t.classList.add(`drag-over`)},this.onRailDrop=e=>{if(e.preventDefault(),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);if(t===null||t.dataset.railItem===this.dragItem){this.dragItem=void 0;return}let n=t.dataset.railItem;if(n===void 0||!tH(n)){this.dragItem=void 0;return}let r=[...this.railOrder],i=r.indexOf(this.dragItem),a=r.indexOf(n);if(i===-1||a===-1){this.dragItem=void 0;return}r.splice(i,1),r.splice(a,0,this.dragItem),this.railOrder=r,this.onRailOrderChange?.(r),this.dragItem=void 0},typeof window<`u`&&`matchMedia`in window&&(this.desktopMedia=window.matchMedia(cw))}connectedCallback(){super.connectedCallback(),this.desktopMedia?.addEventListener(`change`,this.onDesktopMediaChange)}disconnectedCallback(){super.disconnectedCallback(),this.desktopMedia?.removeEventListener(`change`,this.onDesktopMediaChange)}updated(e){!e.has(`compactOpen`)||!this.compactOpen||this.isDesktopRailLayout()||this.renderRoot.querySelector(`.compact-rail-close`)?.focus()}isDesktopRailLayout(){return this.desktopMedia?.matches??!0}closeCompactBeforeAction(){this.isDesktopRailLayout()||this.onCloseCompact?.()}invokeCoreAction(e){this.closeCompactBeforeAction(),e?.()}resolveDragTarget(e){if(e===null||!(e instanceof HTMLElement))return null;let t=e.closest(`[data-rail-item]`);return t instanceof HTMLElement?t:null}dndProps(e){return{draggable:`true`,"data-rail-item":e}}renderReorderableButton(e){switch(e){case`terminal`:return this.renderTerminalButton();case`git-update-manager`:return this.renderGitUpdateManagerButton();case`theme`:return this.renderThemeButton();case`system-prompt`:return this.renderSystemPromptButton();case`history`:return this.renderHistoryButton();case`info`:return this.renderInfoButton()}}renderTerminalButton(){let e=this.dndProps(`terminal`),t=this.terminalCount>0?this.terminalCount:void 0,n=t===void 0?``:`${String(t)} active terminal${t===1?``:`s`}`;return g`
|
|
7053
7066
|
<button
|
|
7054
7067
|
type="button"
|
|
7055
7068
|
class="icon-button terminal-button"
|
|
@@ -7174,6 +7187,23 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7174
7187
|
<path d="M12 17v4"/>
|
|
7175
7188
|
</svg>
|
|
7176
7189
|
</button>
|
|
7190
|
+
`}renderReloadButton(){return g`
|
|
7191
|
+
<button
|
|
7192
|
+
type="button"
|
|
7193
|
+
class="icon-button rail-reload-button"
|
|
7194
|
+
title="Full page reload"
|
|
7195
|
+
aria-label="Full page reload"
|
|
7196
|
+
@click=${this.reloadApp}
|
|
7197
|
+
>
|
|
7198
|
+
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
|
7199
|
+
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
|
7200
|
+
aria-hidden="true" focusable="false">
|
|
7201
|
+
<path d="M20 6v5h-5"/>
|
|
7202
|
+
<path d="M4 18v-5h5"/>
|
|
7203
|
+
<path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"/>
|
|
7204
|
+
<path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"/>
|
|
7205
|
+
</svg>
|
|
7206
|
+
</button>
|
|
7177
7207
|
`}renderSettingsButton(){return g`
|
|
7178
7208
|
<button
|
|
7179
7209
|
type="button"
|
|
@@ -7207,6 +7237,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7207
7237
|
${this.pluginItems.map(e=>this.renderPluginButton(e))}
|
|
7208
7238
|
`}
|
|
7209
7239
|
<div class="rail-spacer"></div>
|
|
7240
|
+
${this.showReload?this.renderReloadButton():v}
|
|
7210
7241
|
${this.renderSettingsButton()}
|
|
7211
7242
|
`}renderCompactCloseButton(){return g`
|
|
7212
7243
|
<button
|
|
@@ -7316,7 +7347,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7316
7347
|
.compact-rail-dialog { height: 100%; }
|
|
7317
7348
|
.compact-rail-dialog .rail { box-shadow: 8px 0 24px var(--pi-shadow); }
|
|
7318
7349
|
.compact-rail-close { margin-bottom: 2px; }
|
|
7319
|
-
`}};H([x({attribute:!1})],rH.prototype,`onOpenTerminal`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenGitUpdateManager`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenTheme`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenSystemPrompt`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenHistory`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenInfo`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenSettings`,void 0),H([x({type:Number})],rH.prototype,`terminalCount`,void 0),H([x({type:Number})],rH.prototype,`gitUpdateManagerCount`,void 0),H([x({type:Boolean})],rH.prototype,`systemPromptEnabled`,void 0),H([x({type:Boolean})],rH.prototype,`historyEnabled`,void 0),H([x({attribute:!1})],rH.prototype,`railOrder`,void 0),H([x({attribute:!1})],rH.prototype,`onRailOrderChange`,void 0),H([x({attribute:!1})],rH.prototype,`pluginItems`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenPluginActivity`,void 0),H([x({type:Boolean})],rH.prototype,`compactOpen`,void 0),H([x({attribute:!1})],rH.prototype,`onCloseCompact`,void 0),rH=H([b(`activity-rail`)],rH);var iH=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},aH=class extends y{constructor(...e){super(...e),this.close=()=>{this.onClose?.()},this.handleCancel=e=>{e.preventDefault(),this.close()},this.handleBackdropClick=e=>{e.target===e.currentTarget&&this.close()}}firstUpdated(){let e=this.nativeDialog;e?.isConnected===!0&&(e.showModal(),this.closeButton?.focus())}disconnectedCallback(){let e=this.nativeDialog;e?.open===!0&&e.close(),super.disconnectedCallback()}render(){let e=Ix(this.activity,this.context,this.onReportError??iH);return g`
|
|
7350
|
+
`}};H([x({attribute:!1})],rH.prototype,`onOpenTerminal`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenGitUpdateManager`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenTheme`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenSystemPrompt`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenHistory`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenInfo`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenSettings`,void 0),H([x({type:Number})],rH.prototype,`terminalCount`,void 0),H([x({type:Number})],rH.prototype,`gitUpdateManagerCount`,void 0),H([x({type:Boolean})],rH.prototype,`systemPromptEnabled`,void 0),H([x({type:Boolean})],rH.prototype,`historyEnabled`,void 0),H([x({attribute:!1})],rH.prototype,`railOrder`,void 0),H([x({attribute:!1})],rH.prototype,`onRailOrderChange`,void 0),H([x({attribute:!1})],rH.prototype,`pluginItems`,void 0),H([x({attribute:!1})],rH.prototype,`onOpenPluginActivity`,void 0),H([x({type:Boolean})],rH.prototype,`compactOpen`,void 0),H([x({attribute:!1})],rH.prototype,`onCloseCompact`,void 0),H([x({attribute:!1})],rH.prototype,`onReload`,void 0),H([x({type:Boolean})],rH.prototype,`showReload`,void 0),rH=H([b(`activity-rail`)],rH);var iH=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},aH=class extends y{constructor(...e){super(...e),this.close=()=>{this.onClose?.()},this.handleCancel=e=>{e.preventDefault(),this.close()},this.handleBackdropClick=e=>{e.target===e.currentTarget&&this.close()}}firstUpdated(){let e=this.nativeDialog;e?.isConnected===!0&&(e.showModal(),this.closeButton?.focus())}disconnectedCallback(){let e=this.nativeDialog;e?.open===!0&&e.close(),super.disconnectedCallback()}render(){let e=Ix(this.activity,this.context,this.onReportError??iH);return g`
|
|
7320
7351
|
<dialog
|
|
7321
7352
|
class="plugin-activity-backdrop"
|
|
7322
7353
|
role="dialog"
|
|
@@ -7477,7 +7508,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7477
7508
|
.git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
|
|
7478
7509
|
.git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
|
|
7479
7510
|
}
|
|
7480
|
-
`}};H([x({attribute:!1})],oH.prototype,`onClose`,void 0),H([x({attribute:!1})],oH.prototype,`onStatusChange`,void 0),H([x({attribute:!1})],oH.prototype,`workspace`,void 0),H([x()],oH.prototype,`machineId`,void 0),H([x({attribute:!1})],oH.prototype,`api`,void 0),H([S()],oH.prototype,`status`,void 0),H([S()],oH.prototype,`selectedChange`,void 0),H([S()],oH.prototype,`selectedDiff`,void 0),H([S()],oH.prototype,`loadingStatus`,void 0),H([S()],oH.prototype,`loadingDiff`,void 0),H([S()],oH.prototype,`error`,void 0),H([S()],oH.prototype,`bounds`,void 0),oH=H([b(`git-update-manager-panel`)],oH);function sH(){NS(()=>import(`./UnifiedDiffViewer-B7xq-ET5.js`),[],import.meta.url)}function cH(e,t){let n=hf(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function lH(e){return e===`staged`?`Staged`:`Unstaged`}function uH(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function dH(e){return e instanceof Error?e.message:String(e)}var fH=900*1e3,pH=750,mH=[1e3,3e3,8e3,15e3,3e4],hH={capture:!0},gH=`auto:on`,_H=`auto:off`,vH=`theme:`,yH=Ad(`core:workspace.files`),bH=Ad(`core:workspace.git`),xH=Ad(`core:workspace.terminal`),SH=`workspace-memory`,CH=`workspace.memory`,wH=`workspace-memory:workspace.memory`,TH=`workspace-learned-skills`,EH=`workspace.learned-skills`,DH=`workspace-learned-skills:workspace.learned-skills`,OH=`workspace-tasks`,kH=`workspace.tasks`,AH=320,jH=2,MH=`(min-width: 1181px)`,NH=75,PH=`Could not remember this model policy for future sessions.`,$=class extends y{constructor(e={}){super(),this.state=_d(),this.sessionUnread=new bx({onChange:e=>{R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new t_(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.hostSpeech=new s_({onStateChange:()=>{this.hostSpeechSurfaceVisible()&&this.requestUpdate()}}),this.sessions=new ng(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Lh,{refreshProjectSessionCatalog:()=>this.projectCatalog.refresh(),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)},onStarterModelPolicyConfirmed:e=>{this.handleStarterModelPolicyConfirmed(e)},onStarterModelPolicySubstitution:e=>{this.handleStarterModelPolicySubstitution(e)}}),this.workspaces=new fy(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new uy,{onForgetProject:(e,t)=>{this.files.forgetScope(e,t)},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new jf(()=>this.state,{workspaces:Oc.workspaces,applySnapshot:async e=>{await this.workspaces.reconcileProjectCatalog(e)},captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectActivityOwnership=new Hf(()=>this.state,e=>{this.setState(e)},{api:Oc,captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onProjectTopology:async e=>{let t=this.state.projects.find(t=>t.id===e.projectId&&t.path===e.projectPath);t!==void 0&&await this.workspaces.reconcileProjectCatalog({machineId:e.machineId,project:t,workspaces:e.workspaces,...e.topologyRequest===void 0?{}:{topologyRequest:e.topologyRequest}})},onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Cd(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Dd(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Df(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e),this.recentProjects.load()}}),this.machines=new Cf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Wf(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new $d(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new of(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new pf(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new lf(()=>this.state,e=>{this.setState(e)}),this.recentProjects=new Nf({machineId:()=>R(this.state),onChange:()=>{this.requestUpdate()},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.keyboard=new bb,this.realtime=new sh,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new nb,this.terminalSelection=new hb,this.appShell=new lw(this),this.browserResume=new fw({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq=0,this.isSpeechInputSettingsRequestCurrent=e=>this.speechInputSettingsConnected&&e===this.speechInputSettingsRequestSeq,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.panelCollapse=new Pw(this),this.panelResize=new Rw(this),this.navigationSections=new jw(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=FH(),this.reportActivityRailError=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Hx()??Rx,this.activeThemeId=Lx,this.isRefreshingApp=!1,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogGeneration=0,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new Kb({save:async(e,t)=>{let n=await kc.updateSessionDefaults(e.cwd,{starterModelPolicyPreference:t},e.machineId),r=this.starterModelPolicyPreferenceScope();return r?.machineId===e.machineId&&r.cwd===e.cwd&&(this.starterModelPolicyPreferenceReadError=``),n},onStateChange:()=>{this.requestUpdate()}}),this.confirmedStarterModelPolicyPreferenceWriter=new Zb({remember:(e,t)=>kc.rememberCurrentModelPolicy(t,e.machineId),onRemembered:(e,t,n)=>{this.handleConfirmedStarterModelPolicyRemembered(e,t,n)},onStateChange:(e,t)=>{this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)&&this.confirmedStarterModelPolicyUiGeneration===this.starterModelPolicySelectionGeneration&&(!t.saving&&t.error===void 0&&(this.starterModelPolicyPreferenceReadError=``),this.requestUpdate())}}),this.starterModelPolicySelectionGeneration=0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``,this.activeModelPolicyApplyGeneration=0,this.modelTierCatalogSeq=0,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.statisticsLoading=!1,this.statisticsRequestGeneration=0,this.sessionBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=kT(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=LT(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=QV()??[...KV],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=aT(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=eu(void 0),this.sessionWarningVisibility=Ox(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onTerminalModalViewportResize=()=>{this.terminalModalBounds!==void 0&&(this.terminalModalBounds=ST(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{if(e.key===`Escape`&&this.promptEditor?.cancelSpeechInput()===!0){e.preventDefault(),e.stopPropagation();return}this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.state.actionPaletteOpen||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.closeCompactActivityRail=()=>{if(!this.compactRailOpen)return;this.compactRailOpen=!1;let e=this.compactActivityRailLauncher;this.updateComplete.then(()=>{!this.compactRailOpen&&this.activeActivityRailId===void 0&&(e===void 0?this.currentCompactActivityRailLauncher()?.focus():this.restoreActivityRailFocus(e))})},this.toggleCompactActivityRail=e=>{this.appShell.isDesktopActivityRailLayout||(!this.compactRailOpen&&e!==void 0&&(this.compactActivityRailLauncher=e),this.compactRailOpen=!this.compactRailOpen)},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;if(this.starterModelPolicyBlocksStart()){let e=this.starterNoticeScope();e!==void 0&&this.publishStarterNotice(ed(e));return}this.starterNotice=void 0;let i=this.state.selectedWorkspace?.id,a=R(this.state),o=this.selectedProjectWorkTarget(a),s=this.starterModelPolicy,c=this.starterModelPolicyInputs()?.decision,l=c?.kind===`fallback`?c.requested:this.starterPlusModelPolicyInitializer();this.starterModelPolicySelectionSupported(a)&&l===void 0||((l===void 0?this.sessions.startSessionWithPrompt(e,t,n,r,this.starterModelPolicyStartSnapshot(),e=>{this.clearStarterModelPolicyAfterSuccessfulStart(e,i,s)}):this.sessions.startPlusSessionWithPrompt(e,t,n,r??`inline`,l,()=>void 0)).then(e=>{e&&this.recordProjectWork(o)}).catch(e=>{i!==void 0&&this.publishStarterNotice(td(`start-failed`,`Could not start the session. ${pU(e)}`,{machineId:a,workspaceId:i}))}),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleSelectStarterPolicyMode=async e=>{let t=this.starterModelPolicy;if(t===void 0||t.mode===e)return;if(this.starterModelPolicySelectionSupported()){let n=e===`exact`?ku(t):t.tier===void 0?{...t,mode:`tiered`}:Ou(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(R(this.state));return}if(e===`exact`){let e=ku(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:Cu(n);r!==void 0&&Du(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:Ou(t,t.tier),r=this.setStarterModelPolicyDraft(n);if(n.tier===void 0){this.ensureModelTierCatalog(R(this.state));return}let i=await this.ensureStarterModelPolicyCatalog();this.starterModelPolicy!==r||i===void 0||Mu(r,i)!==void 0&&this.persistStarterModelPolicyPreference(r)},this.handleSelectStarterPolicyTier=async e=>{let t=this.starterModelPolicy,n=await this.ensureStarterModelPolicyCatalog();if(t===void 0||t!==this.starterModelPolicy||n===void 0)return;let r=Ou(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}Mu(r,n)!==void 0&&(this.setStarterModelPolicyDraft(r),this.persistStarterModelPolicyPreference(r))},this.handleSelectStarterPolicyThinking=async e=>{await this.pickStarterThinking(e)},this.handleSelectActivePolicyMode=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(!(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode===e)){if(this.cancelActiveModelPolicyApply(),e===`exact`){this.setActiveModelPolicyDraft(ku(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(Ou(t,t.tier)),await this.applyActiveModelPolicyDraft()}},this.handleSelectActivePolicyTier=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state))return;this.cancelActiveModelPolicyApply();let n=Ou(t,e);this.setActiveModelPolicyDraft(n),await this.applyActiveModelPolicyDraft()},this.handleSelectActivePolicyThinking=async e=>{await this.pickThinking(e)},this.handleOpenTerminalFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.closeCompactActivityRail(),this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,$V(e)},this.handleCloseTerminalModal=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalOpen=!1},this.toggleTerminalModalMaximized=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalMaximized=!this.terminalModalMaximized},this.handleTerminalModalMovePointerDown=e=>{this.startTerminalModalPointerInteraction(`move`,e)},this.handleTerminalModalResizePointerDown=e=>{this.startTerminalModalPointerInteraction(`resize`,e)},this.handleTerminalModalPointerMove=e=>{let t=this.terminalModalPointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY},r=this.terminalModalViewport();this.terminalModalBounds=t.operation===`move`?bT(t.bounds,n,r):xT(t.bounds,n,r)},this.handleTerminalModalPointerUp=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishTerminalModalPointerInteraction())},this.handleTerminalModalPointerCancel=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&this.finishTerminalModalPointerInteraction()},this.adjustTerminalFontSize=e=>{let t=DT(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=OT(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleToggleHostSpeech=e=>{let t=this.state.selectedSession;if(t===void 0||R(this.state)!==`local`)return;let n=this.hostSpeech.snapshot.active;if(n?.sessionId===t.id&&n.messageKey===e.messageKey){this.hostSpeech.stop();return}this.hostSpeech.startManual({machineId:`local`,sessionId:t.id,messageKey:e.messageKey,text:e.text})},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Nx(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()},this.speechInputSettingsApi=e.speechInputApi??Qs,this.createSpeechInputSettingsChannel=e.createSpeechInputSettingsChannel??(e=>new vw(e)),this.workspaceTasks=(e.createWorkspaceTasksController??(e=>new Dy(e)))({selectedScope:()=>eU(this.state),onChange:()=>{this.requestUpdate()}})}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncStarterNotice()}updated(){this.committedChatIdentity=RH(this.state),this.syncSelectedSessionReadState(),this.compactRailOpen&&this.appShell.isDesktopActivityRailLayout&&this.closeCompactActivityRail();let e=this.activeActivityRailId;e!==void 0&&this.activeActivityRailItem()===void 0&&this.closeActivityRailItem(e,this.activeActivityRailGeneration)}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Ax(this.sessionWarningVisibility,e===void 0?void 0:xd(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=LH(e,t);await this.updateComplete,!(!this.unreadConnected||RH(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);sU(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=UT(this.state.selectedProject?.name);this.windowTitleCleanup=WT(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=LH(e,t);return RH(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.historyWindow!==void 0||this.modelsConfigDialogOpen||this.skillsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.pluginsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.systemPromptDialogOpen&&this.state.selectedSession!==void 0||this.state.actionPaletteOpen||this.projectBrowserOpen||this.statisticsProject!==void 0||this.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen||this.recentProjectDialogEntry!==void 0}hostSpeechSurfaceVisible(){return R(this.state)===`local`?this.settingsSection===`general`||this.state.selectedSession!==void 0&&!this.isChatObscured():!1}abandonHostSpeechIfSourceInvalid(e){let t=this.hostSpeech.snapshot.active;if(t===void 0)return;let n=e.selectedSession;if(n?.id!==t.sessionId)return;if(n.archived===!0){this.hostSpeech.stop();return}let r=sy({messages:e.messages,messagePageStart:e.messagePageStart},t.messageKey);(r===``||!this.hostSpeech.matchesActiveSource({sessionId:t.sessionId,messageKey:t.messageKey,text:r}))&&this.hostSpeech.stop()}connectedCallback(){super.connectedCallback(),this.connectSpeechInputSettings(),this.hostSpeech.select(zH(this.state)),this.hostSpeech.refreshStatus(),this.synchronizeProjectCatalogPolling(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,hH),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},fH),this.refreshWorkspaceActivity(),this.recentProjects.load(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.synchronizeWorkspaceTasksObservationForSelectedWorkspace(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.disconnectSpeechInputSettings(),this.finishTerminalModalPointerInteraction(),this.hostSpeech.dispose(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,hH),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.resetActiveModelPolicyDraft(),this.sessions.dispose(),this.projectCatalog.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.memory.dispose(),this.learnedSkills.dispose(),this.piWebUiStatusTimer!==void 0&&window.clearInterval(this.piWebUiStatusTimer),this.piWebUiStatusTimer=void 0,this.clearScheduledPiWebUiStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),this.disconnectWindowTitle(),this.workspaceTasks.observe(!1),this.workspaceTasks.dispose(),super.disconnectedCallback()}setState(e){if(!oU(this.state,e))return;let t=this.state,n={...t,...e},r=zH(t),i=zH(n);BH(r,i)?t.status?.isCompacting!==!0&&n.status?.isCompacting===!0?this.hostSpeech.stop():this.abandonHostSpeechIfSourceInvalid(n):this.hostSpeech.select(i);let a=VH(t),o=UH(t),s=HH(t);this.state=n,this.synchronizeFileNavigation(t,n),s!==HH(this.state)&&(this.starterModelPolicySelectionGeneration+=1),a!==VH(this.state)&&this.resetActiveModelPolicyDraft(),RH(t)!==RH(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),nU(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),!this.shouldShowSessionStartScreen(t)&&this.shouldShowSessionStartScreen(this.state)&&this.state.selectedWorkspace!==void 0&&this.loadStarterSessionDefaults(this.state.selectedWorkspace),this.handleMachineChange(t,this.state),this.handleStarterModelPolicyCapabilityChange(t,this.state),rU(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let c=UH(this.state);c!==void 0&&c!==o&&this.preloadActiveModelPolicyInputs()}synchronizeFileNavigation(e,t){Jd(e)!==Jd(t)&&(this.files.workspaceChanged(),!this.routeRestoreInProgress&&t.selectedWorkspace!==void 0&&this.files.restoreRememberedFile())}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=eT();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()}connectSpeechInputSettings(){if(!this.speechInputSettingsConnected){this.speechInputSettingsConnected=!0;try{this.speechInputSettingsChannel=this.createSpeechInputSettingsChannel(e=>{this.handleSpeechInputSettingsChannelRevision(e)})}catch{this.speechInputSettingsChannel=void 0}this.refreshSpeechInputSettings()}}disconnectSpeechInputSettings(){!this.speechInputSettingsConnected&&this.speechInputSettingsChannel===void 0||(this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq+=1,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannel?.close(),this.speechInputSettingsChannel=void 0)}async refreshSpeechInputSettings(){if(!this.speechInputSettingsConnected)return;let e=++this.speechInputSettingsRequestSeq;try{let t=await this.speechInputSettingsApi.settings();if(e!==this.speechInputSettingsRequestSeq)return;this.speechInputSettings=t}catch{}}handleSpeechInputSettingsLoaded(e){this.adoptSpeechInputSettings(e,!1)}handleSpeechInputSettingsSaved(e){this.adoptSpeechInputSettings(e,!0)}adoptSpeechInputSettings(e,t){this.speechInputSettingsConnected&&(this.speechInputSettingsRequestSeq+=1,this.speechInputSettings=e,this.pendingSpeechInputSettingsChannelRevision===e.revision&&(this.pendingSpeechInputSettingsChannelRevision=void 0),t&&this.speechInputSettingsChannel?.publish(e.revision))}handleSpeechInputSettingsChannelRevision(e){!this.speechInputSettingsConnected||e===this.speechInputSettings?.revision||(this.pendingSpeechInputSettingsChannelRevision=e,!(this.speechInputSettingsChannelRefreshInFlight||this.speechInputSettingsChannelDispatchQueued)&&(this.speechInputSettingsChannelDispatchQueued=!0,queueMicrotask(()=>{this.speechInputSettingsChannelDispatchQueued=!1,!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.refreshSpeechInputSettingsFromChannel()})))}async refreshSpeechInputSettingsFromChannel(){if(!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.pendingSpeechInputSettingsChannelRevision!==void 0){this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannelRefreshInFlight=!0;try{await this.refreshSpeechInputSettings()}finally{this.speechInputSettingsChannelRefreshInFlight=!1,this.shouldRunSpeechInputSettingsChannelTrailingRefresh()&&this.refreshSpeechInputSettingsFromChannel()}}}shouldRunSpeechInputSettingsChannelTrailingRefresh(){return this.speechInputSettingsConnected&&this.pendingSpeechInputSettingsChannelRevision!==void 0}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.refreshSpeechInputSettings()])}schedulePiWebUiStatusRefresh(e=pH){this.clearScheduledPiWebUiStatusRefresh(),this.piWebUiStatusDeferredTimer=window.setTimeout(()=>{this.piWebUiStatusDeferredTimer=void 0,this.piWebUiStatusController.refresh()},e)}clearScheduledPiWebUiStatusRefresh(){this.piWebUiStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebUiStatusDeferredTimer),this.piWebUiStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>aU(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await sc.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=eu(e),this.hostSpeech.configure(e.tts)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(eT(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?uU():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),R(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?uU():{selectedFilePath:Md(yH,`file`),selectedDiffPath:Md(bH,`diff`),selectedTerminalId:Md(xH,`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){tT(e,{replace:!0}),Nd(yH,`file`,void 0,{replace:!0}),Nd(bH,`diff`,void 0,{replace:!0}),Nd(xH,`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=fU(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>=mH.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){await this.files.restoreRememberedFile(t),(e??this.state.workspaceTool)===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await gU(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),tT({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(ib(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(ib(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){tT(ab(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Nd(yH,`file`,e.selectedFilePath,{replace:!0}),Nd(bH,`diff`,e.selectedDiffPath,{replace:!0}),Nd(xH,`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)??rb(e.id);if(await this.restoreRouteFor(ab(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==``}openWorkspaceTool(e){e===`core:workspace.terminal`&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=R(this.state)){let n=dU(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=fT(e,{api:{runTerminalCommand:(e,n)=>Ac.runTerminalCommand(e,n,t),listCommandRuns:e=>Ac.listCommandRuns(e,t),getCommandRun:e=>Ac.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}}),a={...i,runCommand:async e=>{let n=await i.runCommand(e);return this.recordProjectWork({machineId:t,projectId:e.workspace.projectId}),n}};return this.terminalCommandRunRuntimes.set(n,a),a}async openRuntimeTerminal(e,t,n){return(R(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:`core:workspace.terminal`,view:`core:workspace.terminal`},!1,{selectedTerminalId:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)?(this.setState({error:`Machine not found for terminal command run`}),!1):(this.openTerminal(n),!0)}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){Nd(xH,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e=`general`){this.settingsSection=e,oT(e)}closeSettings(){this.settingsSection=void 0,oT(void 0)}navigateSettings(e){this.settingsSection=e,oT(e)}restoreSettingsRoute(){this.settingsSection=aT()}handleWorkspaceChange(e,t){let n=tU(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&(this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.synchronizeWorkspaceTasksObservationForSelectedWorkspace());return}this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let r=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));if(this.setState({activeTerminalCount:0,selectedTerminalId:r}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(r,{replace:!0})),t.selectedWorkspace===void 0){this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.synchronizeWorkspaceTasksObservationForSelectedWorkspace();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.synchronizeWorkspaceTasksObservationForSelectedWorkspace()}async loadStarterSessionDefaults(e,t={}){let n=R(this.state),r=++this.starterSessionDefaultsSeq,i=this.starterModelPolicySelectionSupported(n),a=()=>r===this.starterSessionDefaultsSeq&&R(this.state)===n&&this.state.selectedWorkspace?.id===e.id&&this.state.selectedWorkspace.path===e.path&&(t.expectedSelectionGeneration===void 0||this.starterModelPolicySelectionGeneration===t.expectedSelectionGeneration);try{let r=i?await kc.sessionDefaultsV2(e.path,n):await kc.sessionDefaults(e.path,n);if(!a())return;let o=this.starterSessionDefaults;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let s=this.starterModelPolicy;s===void 0||i&&!JH(o)?this.starterModelPolicy=wu(r):i?this.starterModelPolicy=s:this.starterModelPolicy=Tu(s,r),this.completeStarterModelPolicyFromActiveTier();let c=this.starterModelPolicy;if(this.selectedMachineModelTierCatalog()===void 0&&(i||c.mode===`tiered`&&!this.modelTierCatalogLoading)){let e=this.ensureModelTierCatalog(n);t.awaitModelTierCatalog===!0&&await e}}catch(t){a()&&(console.warn(`Failed to load Pi session defaults`,t),this.publishStarterNotice(td(`defaults-failed`,`Could not load this workspace's model defaults. ${pU(t)}`,{machineId:n,workspaceId:e.id})))}}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:E(e,w.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e),this.projectCatalog.refresh()},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new sh;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>iU(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):lU(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let t=this.state.selectedWorkspace;t!==void 0&&(e.type===`terminal.closed`?e.cwd:e.terminal.cwd)===t.path&&(e.type===`terminal.created`&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type===`terminal.closed`?e.terminalId:e.terminal.id),e.type===`terminal.closed`&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){let t=R(this.state);try{let n=await Ac.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=cU(e),r=cU(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??`local`)===(t.selectedMachine?.id??`local`))return;this.closeRecentProjectDialogForMachineChange(),this.closeProjectStatistics(),this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.resetModelTierCatalogForMachineChange(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.recentProjects.load(),this.loadPluginsForSelectedMachine();let n=t.selectedWorkspace;n!==void 0&&this.shouldShowSessionStartScreen(t)&&this.loadStarterSessionDefaults(n)}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){return g`
|
|
7511
|
+
`}};H([x({attribute:!1})],oH.prototype,`onClose`,void 0),H([x({attribute:!1})],oH.prototype,`onStatusChange`,void 0),H([x({attribute:!1})],oH.prototype,`workspace`,void 0),H([x()],oH.prototype,`machineId`,void 0),H([x({attribute:!1})],oH.prototype,`api`,void 0),H([S()],oH.prototype,`status`,void 0),H([S()],oH.prototype,`selectedChange`,void 0),H([S()],oH.prototype,`selectedDiff`,void 0),H([S()],oH.prototype,`loadingStatus`,void 0),H([S()],oH.prototype,`loadingDiff`,void 0),H([S()],oH.prototype,`error`,void 0),H([S()],oH.prototype,`bounds`,void 0),oH=H([b(`git-update-manager-panel`)],oH);function sH(){NS(()=>import(`./UnifiedDiffViewer-CIfQkwSQ.js`),[],import.meta.url)}function cH(e,t){let n=hf(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function lH(e){return e===`staged`?`Staged`:`Unstaged`}function uH(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function dH(e){return e instanceof Error?e.message:String(e)}var fH=900*1e3,pH=750,mH=[1e3,3e3,8e3,15e3,3e4],hH={capture:!0},gH=`auto:on`,_H=`auto:off`,vH=`theme:`,yH=Ad(`core:workspace.files`),bH=Ad(`core:workspace.git`),xH=Ad(`core:workspace.terminal`),SH=`workspace-memory`,CH=`workspace.memory`,wH=`workspace-memory:workspace.memory`,TH=`workspace-learned-skills`,EH=`workspace.learned-skills`,DH=`workspace-learned-skills:workspace.learned-skills`,OH=`workspace-tasks`,kH=`workspace.tasks`,AH=320,jH=2,MH=`(min-width: 1181px)`,NH=75,PH=`Could not remember this model policy for future sessions.`,$=class extends y{constructor(e={}){super(),this.state=_d(),this.sessionUnread=new bx({onChange:e=>{R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new t_(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.hostSpeech=new s_({onStateChange:()=>{this.hostSpeechSurfaceVisible()&&this.requestUpdate()}}),this.sessions=new ng(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Lh,{refreshProjectSessionCatalog:()=>this.projectCatalog.refresh(),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)},onStarterModelPolicyConfirmed:e=>{this.handleStarterModelPolicyConfirmed(e)},onStarterModelPolicySubstitution:e=>{this.handleStarterModelPolicySubstitution(e)}}),this.workspaces=new fy(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new uy,{onForgetProject:(e,t)=>{this.files.forgetScope(e,t)},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new jf(()=>this.state,{workspaces:Oc.workspaces,applySnapshot:async e=>{await this.workspaces.reconcileProjectCatalog(e)},captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectActivityOwnership=new Hf(()=>this.state,e=>{this.setState(e)},{api:Oc,captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onProjectTopology:async e=>{let t=this.state.projects.find(t=>t.id===e.projectId&&t.path===e.projectPath);t!==void 0&&await this.workspaces.reconcileProjectCatalog({machineId:e.machineId,project:t,workspaces:e.workspaces,...e.topologyRequest===void 0?{}:{topologyRequest:e.topologyRequest}})},onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Cd(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Dd(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Df(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e),this.recentProjects.load()}}),this.machines=new Cf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Wf(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new $d(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new of(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new pf(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new lf(()=>this.state,e=>{this.setState(e)}),this.recentProjects=new Nf({machineId:()=>R(this.state),onChange:()=>{this.requestUpdate()},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.keyboard=new bb,this.realtime=new sh,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new nb,this.terminalSelection=new hb,this.appShell=new lw(this),this.browserResume=new fw({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq=0,this.isSpeechInputSettingsRequestCurrent=e=>this.speechInputSettingsConnected&&e===this.speechInputSettingsRequestSeq,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.panelCollapse=new Pw(this),this.panelResize=new Rw(this),this.navigationSections=new jw(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=FH(),this.reportActivityRailError=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Hx()??Rx,this.activeThemeId=Lx,this.isRefreshingApp=!1,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogGeneration=0,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new Kb({save:async(e,t)=>{let n=await kc.updateSessionDefaults(e.cwd,{starterModelPolicyPreference:t},e.machineId),r=this.starterModelPolicyPreferenceScope();return r?.machineId===e.machineId&&r.cwd===e.cwd&&(this.starterModelPolicyPreferenceReadError=``),n},onStateChange:()=>{this.requestUpdate()}}),this.confirmedStarterModelPolicyPreferenceWriter=new Zb({remember:(e,t)=>kc.rememberCurrentModelPolicy(t,e.machineId),onRemembered:(e,t,n)=>{this.handleConfirmedStarterModelPolicyRemembered(e,t,n)},onStateChange:(e,t)=>{this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)&&this.confirmedStarterModelPolicyUiGeneration===this.starterModelPolicySelectionGeneration&&(!t.saving&&t.error===void 0&&(this.starterModelPolicyPreferenceReadError=``),this.requestUpdate())}}),this.starterModelPolicySelectionGeneration=0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``,this.activeModelPolicyApplyGeneration=0,this.modelTierCatalogSeq=0,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.statisticsLoading=!1,this.statisticsRequestGeneration=0,this.sessionBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=kT(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=LT(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=QV()??[...KV],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=aT(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=eu(void 0),this.sessionWarningVisibility=Ox(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onTerminalModalViewportResize=()=>{this.terminalModalBounds!==void 0&&(this.terminalModalBounds=ST(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{if(e.key===`Escape`&&this.promptEditor?.cancelSpeechInput()===!0){e.preventDefault(),e.stopPropagation();return}this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.state.actionPaletteOpen||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.closeCompactActivityRail=()=>{if(!this.compactRailOpen)return;this.compactRailOpen=!1;let e=this.compactActivityRailLauncher;this.updateComplete.then(()=>{!this.compactRailOpen&&this.activeActivityRailId===void 0&&(e===void 0?this.currentCompactActivityRailLauncher()?.focus():this.restoreActivityRailFocus(e))})},this.toggleCompactActivityRail=e=>{this.appShell.isDesktopActivityRailLayout||(!this.compactRailOpen&&e!==void 0&&(this.compactActivityRailLauncher=e),this.compactRailOpen=!this.compactRailOpen)},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;if(this.starterModelPolicyBlocksStart()){let e=this.starterNoticeScope();e!==void 0&&this.publishStarterNotice(ed(e));return}this.starterNotice=void 0;let i=this.state.selectedWorkspace?.id,a=R(this.state),o=this.selectedProjectWorkTarget(a),s=this.starterModelPolicy,c=this.starterModelPolicyInputs()?.decision,l=c?.kind===`fallback`?c.requested:this.starterPlusModelPolicyInitializer();this.starterModelPolicySelectionSupported(a)&&l===void 0||((l===void 0?this.sessions.startSessionWithPrompt(e,t,n,r,this.starterModelPolicyStartSnapshot(),e=>{this.clearStarterModelPolicyAfterSuccessfulStart(e,i,s)}):this.sessions.startPlusSessionWithPrompt(e,t,n,r??`inline`,l,()=>void 0)).then(e=>{e&&this.recordProjectWork(o)}).catch(e=>{i!==void 0&&this.publishStarterNotice(td(`start-failed`,`Could not start the session. ${pU(e)}`,{machineId:a,workspaceId:i}))}),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleSelectStarterPolicyMode=async e=>{let t=this.starterModelPolicy;if(t===void 0||t.mode===e)return;if(this.starterModelPolicySelectionSupported()){let n=e===`exact`?ku(t):t.tier===void 0?{...t,mode:`tiered`}:Ou(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(R(this.state));return}if(e===`exact`){let e=ku(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:Cu(n);r!==void 0&&Du(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:Ou(t,t.tier),r=this.setStarterModelPolicyDraft(n);if(n.tier===void 0){this.ensureModelTierCatalog(R(this.state));return}let i=await this.ensureStarterModelPolicyCatalog();this.starterModelPolicy!==r||i===void 0||Mu(r,i)!==void 0&&this.persistStarterModelPolicyPreference(r)},this.handleSelectStarterPolicyTier=async e=>{let t=this.starterModelPolicy,n=await this.ensureStarterModelPolicyCatalog();if(t===void 0||t!==this.starterModelPolicy||n===void 0)return;let r=Ou(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}Mu(r,n)!==void 0&&(this.setStarterModelPolicyDraft(r),this.persistStarterModelPolicyPreference(r))},this.handleSelectStarterPolicyThinking=async e=>{await this.pickStarterThinking(e)},this.handleSelectActivePolicyMode=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(!(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode===e)){if(this.cancelActiveModelPolicyApply(),e===`exact`){this.setActiveModelPolicyDraft(ku(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(Ou(t,t.tier)),await this.applyActiveModelPolicyDraft()}},this.handleSelectActivePolicyTier=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state))return;this.cancelActiveModelPolicyApply();let n=Ou(t,e);this.setActiveModelPolicyDraft(n),await this.applyActiveModelPolicyDraft()},this.handleSelectActivePolicyThinking=async e=>{await this.pickThinking(e)},this.handleOpenTerminalFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.closeCompactActivityRail(),this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,$V(e)},this.handleCloseTerminalModal=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalOpen=!1},this.toggleTerminalModalMaximized=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalMaximized=!this.terminalModalMaximized},this.handleTerminalModalMovePointerDown=e=>{this.startTerminalModalPointerInteraction(`move`,e)},this.handleTerminalModalResizePointerDown=e=>{this.startTerminalModalPointerInteraction(`resize`,e)},this.handleTerminalModalPointerMove=e=>{let t=this.terminalModalPointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY},r=this.terminalModalViewport();this.terminalModalBounds=t.operation===`move`?bT(t.bounds,n,r):xT(t.bounds,n,r)},this.handleTerminalModalPointerUp=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishTerminalModalPointerInteraction())},this.handleTerminalModalPointerCancel=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&this.finishTerminalModalPointerInteraction()},this.adjustTerminalFontSize=e=>{let t=DT(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=OT(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleToggleHostSpeech=e=>{let t=this.state.selectedSession;if(t===void 0||R(this.state)!==`local`)return;let n=this.hostSpeech.snapshot.active;if(n?.sessionId===t.id&&n.messageKey===e.messageKey){this.hostSpeech.stop();return}this.hostSpeech.startManual({machineId:`local`,sessionId:t.id,messageKey:e.messageKey,text:e.text})},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Nx(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()},this.speechInputSettingsApi=e.speechInputApi??Qs,this.createSpeechInputSettingsChannel=e.createSpeechInputSettingsChannel??(e=>new vw(e)),this.workspaceTasks=(e.createWorkspaceTasksController??(e=>new Dy(e)))({selectedScope:()=>eU(this.state),onChange:()=>{this.requestUpdate()}})}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncStarterNotice()}updated(){this.committedChatIdentity=RH(this.state),this.syncSelectedSessionReadState(),this.compactRailOpen&&this.appShell.isDesktopActivityRailLayout&&this.closeCompactActivityRail();let e=this.activeActivityRailId;e!==void 0&&this.activeActivityRailItem()===void 0&&this.closeActivityRailItem(e,this.activeActivityRailGeneration)}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Ax(this.sessionWarningVisibility,e===void 0?void 0:xd(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=LH(e,t);await this.updateComplete,!(!this.unreadConnected||RH(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);sU(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=UT(this.state.selectedProject?.name);this.windowTitleCleanup=WT(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=LH(e,t);return RH(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.historyWindow!==void 0||this.modelsConfigDialogOpen||this.skillsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.pluginsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.systemPromptDialogOpen&&this.state.selectedSession!==void 0||this.state.actionPaletteOpen||this.projectBrowserOpen||this.statisticsProject!==void 0||this.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen||this.recentProjectDialogEntry!==void 0}hostSpeechSurfaceVisible(){return R(this.state)===`local`?this.settingsSection===`general`||this.state.selectedSession!==void 0&&!this.isChatObscured():!1}abandonHostSpeechIfSourceInvalid(e){let t=this.hostSpeech.snapshot.active;if(t===void 0)return;let n=e.selectedSession;if(n?.id!==t.sessionId)return;if(n.archived===!0){this.hostSpeech.stop();return}let r=sy({messages:e.messages,messagePageStart:e.messagePageStart},t.messageKey);(r===``||!this.hostSpeech.matchesActiveSource({sessionId:t.sessionId,messageKey:t.messageKey,text:r}))&&this.hostSpeech.stop()}connectedCallback(){super.connectedCallback(),this.connectSpeechInputSettings(),this.hostSpeech.select(zH(this.state)),this.hostSpeech.refreshStatus(),this.synchronizeProjectCatalogPolling(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,hH),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},fH),this.refreshWorkspaceActivity(),this.recentProjects.load(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.synchronizeWorkspaceTasksObservationForSelectedWorkspace(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.disconnectSpeechInputSettings(),this.finishTerminalModalPointerInteraction(),this.hostSpeech.dispose(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,hH),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.resetActiveModelPolicyDraft(),this.sessions.dispose(),this.projectCatalog.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.memory.dispose(),this.learnedSkills.dispose(),this.piWebUiStatusTimer!==void 0&&window.clearInterval(this.piWebUiStatusTimer),this.piWebUiStatusTimer=void 0,this.clearScheduledPiWebUiStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),this.disconnectWindowTitle(),this.workspaceTasks.observe(!1),this.workspaceTasks.dispose(),super.disconnectedCallback()}setState(e){if(!oU(this.state,e))return;let t=this.state,n={...t,...e},r=zH(t),i=zH(n);BH(r,i)?t.status?.isCompacting!==!0&&n.status?.isCompacting===!0?this.hostSpeech.stop():this.abandonHostSpeechIfSourceInvalid(n):this.hostSpeech.select(i);let a=VH(t),o=UH(t),s=HH(t);this.state=n,this.synchronizeFileNavigation(t,n),s!==HH(this.state)&&(this.starterModelPolicySelectionGeneration+=1),a!==VH(this.state)&&this.resetActiveModelPolicyDraft(),RH(t)!==RH(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),nU(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),!this.shouldShowSessionStartScreen(t)&&this.shouldShowSessionStartScreen(this.state)&&this.state.selectedWorkspace!==void 0&&this.loadStarterSessionDefaults(this.state.selectedWorkspace),this.handleMachineChange(t,this.state),this.handleStarterModelPolicyCapabilityChange(t,this.state),rU(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let c=UH(this.state);c!==void 0&&c!==o&&this.preloadActiveModelPolicyInputs()}synchronizeFileNavigation(e,t){Jd(e)!==Jd(t)&&(this.files.workspaceChanged(),!this.routeRestoreInProgress&&t.selectedWorkspace!==void 0&&this.files.restoreRememberedFile())}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=eT();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()}connectSpeechInputSettings(){if(!this.speechInputSettingsConnected){this.speechInputSettingsConnected=!0;try{this.speechInputSettingsChannel=this.createSpeechInputSettingsChannel(e=>{this.handleSpeechInputSettingsChannelRevision(e)})}catch{this.speechInputSettingsChannel=void 0}this.refreshSpeechInputSettings()}}disconnectSpeechInputSettings(){!this.speechInputSettingsConnected&&this.speechInputSettingsChannel===void 0||(this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq+=1,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannel?.close(),this.speechInputSettingsChannel=void 0)}async refreshSpeechInputSettings(){if(!this.speechInputSettingsConnected)return;let e=++this.speechInputSettingsRequestSeq;try{let t=await this.speechInputSettingsApi.settings();if(e!==this.speechInputSettingsRequestSeq)return;this.speechInputSettings=t}catch{}}handleSpeechInputSettingsLoaded(e){this.adoptSpeechInputSettings(e,!1)}handleSpeechInputSettingsSaved(e){this.adoptSpeechInputSettings(e,!0)}adoptSpeechInputSettings(e,t){this.speechInputSettingsConnected&&(this.speechInputSettingsRequestSeq+=1,this.speechInputSettings=e,this.pendingSpeechInputSettingsChannelRevision===e.revision&&(this.pendingSpeechInputSettingsChannelRevision=void 0),t&&this.speechInputSettingsChannel?.publish(e.revision))}handleSpeechInputSettingsChannelRevision(e){!this.speechInputSettingsConnected||e===this.speechInputSettings?.revision||(this.pendingSpeechInputSettingsChannelRevision=e,!(this.speechInputSettingsChannelRefreshInFlight||this.speechInputSettingsChannelDispatchQueued)&&(this.speechInputSettingsChannelDispatchQueued=!0,queueMicrotask(()=>{this.speechInputSettingsChannelDispatchQueued=!1,!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.refreshSpeechInputSettingsFromChannel()})))}async refreshSpeechInputSettingsFromChannel(){if(!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.pendingSpeechInputSettingsChannelRevision!==void 0){this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannelRefreshInFlight=!0;try{await this.refreshSpeechInputSettings()}finally{this.speechInputSettingsChannelRefreshInFlight=!1,this.shouldRunSpeechInputSettingsChannelTrailingRefresh()&&this.refreshSpeechInputSettingsFromChannel()}}}shouldRunSpeechInputSettingsChannelTrailingRefresh(){return this.speechInputSettingsConnected&&this.pendingSpeechInputSettingsChannelRevision!==void 0}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.refreshSpeechInputSettings()])}schedulePiWebUiStatusRefresh(e=pH){this.clearScheduledPiWebUiStatusRefresh(),this.piWebUiStatusDeferredTimer=window.setTimeout(()=>{this.piWebUiStatusDeferredTimer=void 0,this.piWebUiStatusController.refresh()},e)}clearScheduledPiWebUiStatusRefresh(){this.piWebUiStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebUiStatusDeferredTimer),this.piWebUiStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>aU(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await sc.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=eu(e),this.hostSpeech.configure(e.tts)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(eT(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?uU():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),R(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?uU():{selectedFilePath:Md(yH,`file`),selectedDiffPath:Md(bH,`diff`),selectedTerminalId:Md(xH,`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){tT(e,{replace:!0}),Nd(yH,`file`,void 0,{replace:!0}),Nd(bH,`diff`,void 0,{replace:!0}),Nd(xH,`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=fU(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>=mH.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){await this.files.restoreRememberedFile(t),(e??this.state.workspaceTool)===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await gU(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),tT({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(ib(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(ib(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){tT(ab(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Nd(yH,`file`,e.selectedFilePath,{replace:!0}),Nd(bH,`diff`,e.selectedDiffPath,{replace:!0}),Nd(xH,`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)??rb(e.id);if(await this.restoreRouteFor(ab(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==``}openWorkspaceTool(e){e===`core:workspace.terminal`&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=R(this.state)){let n=dU(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=fT(e,{api:{runTerminalCommand:(e,n)=>Ac.runTerminalCommand(e,n,t),listCommandRuns:e=>Ac.listCommandRuns(e,t),getCommandRun:e=>Ac.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}}),a={...i,runCommand:async e=>{let n=await i.runCommand(e);return this.recordProjectWork({machineId:t,projectId:e.workspace.projectId}),n}};return this.terminalCommandRunRuntimes.set(n,a),a}async openRuntimeTerminal(e,t,n){return(R(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:`core:workspace.terminal`,view:`core:workspace.terminal`},!1,{selectedTerminalId:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)?(this.setState({error:`Machine not found for terminal command run`}),!1):(this.openTerminal(n),!0)}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){Nd(xH,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e=`general`){this.settingsSection=e,oT(e)}closeSettings(){this.settingsSection=void 0,oT(void 0)}navigateSettings(e){this.settingsSection=e,oT(e)}restoreSettingsRoute(){this.settingsSection=aT()}handleWorkspaceChange(e,t){let n=tU(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&(this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.synchronizeWorkspaceTasksObservationForSelectedWorkspace());return}this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let r=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));if(this.setState({activeTerminalCount:0,selectedTerminalId:r}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(r,{replace:!0})),t.selectedWorkspace===void 0){this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.synchronizeWorkspaceTasksObservationForSelectedWorkspace();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.synchronizeWorkspaceTasksObservationForSelectedWorkspace()}async loadStarterSessionDefaults(e,t={}){let n=R(this.state),r=++this.starterSessionDefaultsSeq,i=this.starterModelPolicySelectionSupported(n),a=()=>r===this.starterSessionDefaultsSeq&&R(this.state)===n&&this.state.selectedWorkspace?.id===e.id&&this.state.selectedWorkspace.path===e.path&&(t.expectedSelectionGeneration===void 0||this.starterModelPolicySelectionGeneration===t.expectedSelectionGeneration);try{let r=i?await kc.sessionDefaultsV2(e.path,n):await kc.sessionDefaults(e.path,n);if(!a())return;let o=this.starterSessionDefaults;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let s=this.starterModelPolicy;s===void 0||i&&!JH(o)?this.starterModelPolicy=wu(r):i?this.starterModelPolicy=s:this.starterModelPolicy=Tu(s,r),this.completeStarterModelPolicyFromActiveTier();let c=this.starterModelPolicy;if(this.selectedMachineModelTierCatalog()===void 0&&(i||c.mode===`tiered`&&!this.modelTierCatalogLoading)){let e=this.ensureModelTierCatalog(n);t.awaitModelTierCatalog===!0&&await e}}catch(t){a()&&(console.warn(`Failed to load Pi session defaults`,t),this.publishStarterNotice(td(`defaults-failed`,`Could not load this workspace's model defaults. ${pU(t)}`,{machineId:n,workspaceId:e.id})))}}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:E(e,w.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e),this.projectCatalog.refresh()},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new sh;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>iU(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):lU(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let t=this.state.selectedWorkspace;t!==void 0&&(e.type===`terminal.closed`?e.cwd:e.terminal.cwd)===t.path&&(e.type===`terminal.created`&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type===`terminal.closed`?e.terminalId:e.terminal.id),e.type===`terminal.closed`&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){let t=R(this.state);try{let n=await Ac.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=cU(e),r=cU(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??`local`)===(t.selectedMachine?.id??`local`))return;this.closeRecentProjectDialogForMachineChange(),this.closeProjectStatistics(),this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.resetModelTierCatalogForMachineChange(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.recentProjects.load(),this.loadPluginsForSelectedMachine();let n=t.selectedWorkspace;n!==void 0&&this.shouldShowSessionStartScreen(t)&&this.loadStarterSessionDefaults(n)}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){return g`
|
|
7481
7512
|
<workspace-panel
|
|
7482
7513
|
id="workspace-panel"
|
|
7483
7514
|
.emptyState=${this.state.selectedWorkspace===void 0?this.workspacePanelEmptyState():void 0}
|
|
@@ -7576,7 +7607,6 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7576
7607
|
.workspacesCollapsed=${this.navigationSections.isCollapsed(`workspaces`)}
|
|
7577
7608
|
.sessionsCollapsed=${this.navigationSections.isCollapsed(`sessions`)}
|
|
7578
7609
|
.workspaceLabelItems=${e=>this.workspaceLabelItems(e)}
|
|
7579
|
-
.refreshControl=${this.appShell.shouldShowAppRefreshInHeader()?this.renderAppRefresh():void 0}
|
|
7580
7610
|
.onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
|
|
7581
7611
|
.skillsEnabled=${this.state.selectedWorkspace!==void 0}
|
|
7582
7612
|
.pluginsEnabled=${this.state.selectedWorkspace!==void 0}
|
|
@@ -7759,6 +7789,8 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7759
7789
|
.onOpenSettings=${()=>{this.closeCompactActivityRail(),this.openSettings()}}
|
|
7760
7790
|
.railOrder=${this.railOrder}
|
|
7761
7791
|
.onRailOrderChange=${this.handleRailOrderChange}
|
|
7792
|
+
.showReload=${this.appShell.shouldShowAppRefreshInRail()}
|
|
7793
|
+
.onReload=${()=>{this.hardReloadApp()}}
|
|
7762
7794
|
.pluginItems=${this.activityRailItems()}
|
|
7763
7795
|
.onOpenPluginActivity=${(e,t)=>{this.openActivityRailItem(e,()=>{this.restoreActivityRailFocus(t)})}}
|
|
7764
7796
|
.compactOpen=${this.compactRailOpen}
|