@hyperdreamer/pi-webui 1.24.0 → 1.24.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.
@@ -1,7 +1,7 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-CaRR3heo.js","./vendor-editor-core-vyMPzMNA.js","./vendor-editor-languages-DlEQaRIv.js","./vendor-editor-legacy-CYBnW6ZU.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-DgVx_yzp.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
- `).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`)}}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,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))}var Hd=Ad(`core:workspace.files`),Ud=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??Lc,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??iu,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=R(this.getState()),r=await this.api.workspaceTree(e.id,t.id,``,n),i={...this.getState().expandedDirs};await Promise.all(Object.keys(i).map(async r=>{i[r]=(await this.api.workspaceTree(e.id,t.id,r,n)).entries})),this.setState({fileTree:r.entries,expandedDirs:i,fileTreeStale:!1,error:``})}catch(e){this.setState({error:String(e)})}}async expandDir(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:qd(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,R(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:``})}catch(e){this.setState({error:String(e)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),Nd(Hd,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{let r=await this.api.workspaceFile(t.id,n.id,e,R(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(Wd(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),Nd(Hd,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)})}}}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`Select a workspace before uploading files.`});return}if(e.length===0)return;let i=R(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=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:qd(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(Gd(t)){let e=zd(n,this.now());return this.setUploadBatch(e),e}let r=Kd(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 Wd(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function Gd(e){return e instanceof Ql}function Kd(e){return e instanceof Error?e.message:String(e)}function qd(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var Jd=Ad(`core:workspace.git`),Yd=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(Jd,`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(Jd,`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}},Xd=3e4,Zd={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},Qd=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??Zd,this.pollIntervalMs=n.pollIntervalMs??Xd}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=$d(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 $d(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalSkills:e.globalSkills,projectSkills:e.projectSkills,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}var ef=3e4,tf={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},nf=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??tf,this.pollIntervalMs=n.pollIntervalMs??ef}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=rf(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 rf(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalEntries:e.globalEntries,projectEntries:e.projectEntries,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}function af(e){let t=[],n=[];for(let r of e)df(r.index)&&t.push(uf(r,`staged`,r.index)),ff(r.workingTree)&&n.push(uf(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function of(e){let t=af(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function sf(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 cf(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 lf(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function uf(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function df(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function ff(e){return e!==`unmodified`&&e!==`ignored`}var pf=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:hf(this.getState().machineActivities,r),machineRuntimes:hf(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:mf(this.getState().machineStatuses,e.id),machineRuntimes:mf(this.getState().machineRuntimes,e.id),machineActivities:mf(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 mf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function hf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var gf=`~/workspace`,_f=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(gf,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))}},vf=5e3,yf=`reconcile selected project catalog`,bf={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},xf=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??bf,this.pollIntervalMs=t.pollIntervalMs??vf,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(yf,e)}catch{}}},Sf=`record recent project`,Cf=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:wf(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?.(Sf,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 wf(e){return e instanceof Error?e.message:String(e)}function Tf(e,t){return t[e.path]}function Ef(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Df(e,t,n){return Af(jf(e,t,n))}function Of(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function kf(e){return Af(Object.values(e??{}))}function Af(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function jf(e,t,n){return Object.values(n).filter(n=>Of(e,t,n.cwd))}var Mf=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])=>!Nf(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&&!Nf(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 Nf(e,t,n){return e.some(e=>Of(e,t[e.id]??[],n))}var Pf=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}),Ff(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 Ff(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 If=`pi-webui:cached-new-sessions:v1`,Lf=`browserCachedNew`,Rf=`local`;function zf(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Bf(e,t=Rf,n=zf()){if(e.messageCount!==0||e.archived===!0)return;let r=Kf(n).filter(n=>n.id!==e.id||n.machineId!==t);qf([Vf(e,t),...r],n)}function Vf(e,t=Rf){return{...e,browserCachedNew:!0,machineId:t}}function Hf(e,t=Rf,n=zf()){qf(Kf(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Uf(e,t,n=Rf,r=zf()){let i=new Set(t.map(e=>e.id)),a=Kf(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&qf(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Wf(e){return e!==void 0&&Yf(e)&&e.browserCachedNew===!0}function Gf(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:Rf},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt},...e.creationSource===void 0?{}:{creationSource:e.creationSource}}}function Kf(e=zf()){try{let t=e?.getItem(If);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Jf(e)):[]}catch{return[]}}function qf(e,t=zf()){try{e.length===0?t?.removeItem(If):t?.setItem(If,JSON.stringify(e))}catch{}}function Jf(e){if(!Xf(e))return[];let t=Zf(e,`id`),n=Zf(e,`path`),r=Zf(e,`cwd`),i=Zf(e,`created`),a=Zf(e,`modified`),o=Zf(e,`firstMessage`),s=$f(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=Qf(e,`name`),l=Qf(e,`parentSessionPath`),u=Qf(e,`machineId`)??Rf,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 Yf(e){return Lf in e}function Xf(e){return typeof e==`object`&&!!e}function Zf(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Qf(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function $f(e,t){let n=e[t];return typeof n==`number`?n:void 0}function ep(e){return yp(e.flatMap(ap)).filter(e=>e.parts.length>0)}function tp(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function np(e,t){let n=dp(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=Op(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 rp(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,tp(t,n)]}function ip(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 ap(e){if(sp(e))return[e];if(z(e,`role`)===`bashExecution`)return[np(mp(e),e)];let t=hp(z(e,`role`)),n=gp(Dp(e,`content`),e),r=t===`user`?cp(n):void 0;if(r!==void 0)return r.map(t=>np(t,e));let i=up(e);if(t===`tool`)return[np({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?[np({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=op(e);return c===void 0?s:[...s,np(c,e)]}function op(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return tp(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function sp(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Dp(e,`parts`))}function cp(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=lp(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 lp(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 up(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function dp(e){let t=fp(Dp(e,`timestamp`)),n=pp(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function fp(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 pp(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 mp(e){let t=z(e,`command`)??``,n=Op(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Dp(e,`output`);r!=null&&n.push(``,Ap(r));let i=Dp(e,`exitCode`);i!=null&&n.push(``,`exit ${Ap(i)}`),Op(e,`cancelled`)===!0&&n.push(``,`cancelled`),Op(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=z(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
4
+ `).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,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))}var Hd=Ad(`core:workspace.files`),Ud=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??Lc,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??iu,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=R(this.getState()),r=await this.api.workspaceTree(e.id,t.id,``,n),i={...this.getState().expandedDirs};await Promise.all(Object.keys(i).map(async r=>{i[r]=(await this.api.workspaceTree(e.id,t.id,r,n)).entries})),this.setState({fileTree:r.entries,expandedDirs:i,fileTreeStale:!1,error:``})}catch(e){this.setState({error:String(e)})}}async expandDir(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:qd(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,R(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:``})}catch(e){this.setState({error:String(e)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),Nd(Hd,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{let r=await this.api.workspaceFile(t.id,n.id,e,R(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(Wd(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),Nd(Hd,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)})}}}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`Select a workspace before uploading files.`});return}if(e.length===0)return;let i=R(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=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:qd(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(Gd(t)){let e=zd(n,this.now());return this.setUploadBatch(e),e}let r=Kd(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 Wd(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function Gd(e){return e instanceof Ql}function Kd(e){return e instanceof Error?e.message:String(e)}function qd(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var Jd=Ad(`core:workspace.git`),Yd=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(Jd,`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(Jd,`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}},Xd=3e4,Zd={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},Qd=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??Zd,this.pollIntervalMs=n.pollIntervalMs??Xd}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=$d(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 $d(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalSkills:e.globalSkills,projectSkills:e.projectSkills,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}var ef=3e4,tf={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},nf=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??tf,this.pollIntervalMs=n.pollIntervalMs??ef}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=rf(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 rf(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalEntries:e.globalEntries,projectEntries:e.projectEntries,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}function af(e){let t=[],n=[];for(let r of e)df(r.index)&&t.push(uf(r,`staged`,r.index)),ff(r.workingTree)&&n.push(uf(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function of(e){let t=af(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function sf(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 cf(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 lf(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function uf(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function df(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function ff(e){return e!==`unmodified`&&e!==`ignored`}var pf=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:hf(this.getState().machineActivities,r),machineRuntimes:hf(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:mf(this.getState().machineStatuses,e.id),machineRuntimes:mf(this.getState().machineRuntimes,e.id),machineActivities:mf(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 mf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function hf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var gf=`~/workspace`,_f=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(gf,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))}},vf=5e3,yf=`reconcile selected project catalog`,bf={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},xf=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??bf,this.pollIntervalMs=t.pollIntervalMs??vf,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(yf,e)}catch{}}},Sf=`record recent project`,Cf=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:wf(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?.(Sf,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 wf(e){return e instanceof Error?e.message:String(e)}function Tf(e,t){return t[e.path]}function Ef(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Df(e,t,n){return Af(jf(e,t,n))}function Of(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function kf(e){return Af(Object.values(e??{}))}function Af(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function jf(e,t,n){return Object.values(n).filter(n=>Of(e,t,n.cwd))}var Mf=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])=>!Nf(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&&!Nf(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 Nf(e,t,n){return e.some(e=>Of(e,t[e.id]??[],n))}var Pf=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}),Ff(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 Ff(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 If=`pi-webui:cached-new-sessions:v1`,Lf=`browserCachedNew`,Rf=`local`;function zf(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Bf(e,t=Rf,n=zf()){if(e.messageCount!==0||e.archived===!0)return;let r=Kf(n).filter(n=>n.id!==e.id||n.machineId!==t);qf([Vf(e,t),...r],n)}function Vf(e,t=Rf){return{...e,browserCachedNew:!0,machineId:t}}function Hf(e,t=Rf,n=zf()){qf(Kf(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Uf(e,t,n=Rf,r=zf()){let i=new Set(t.map(e=>e.id)),a=Kf(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&qf(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Wf(e){return e!==void 0&&Yf(e)&&e.browserCachedNew===!0}function Gf(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:Rf},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt},...e.creationSource===void 0?{}:{creationSource:e.creationSource}}}function Kf(e=zf()){try{let t=e?.getItem(If);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Jf(e)):[]}catch{return[]}}function qf(e,t=zf()){try{e.length===0?t?.removeItem(If):t?.setItem(If,JSON.stringify(e))}catch{}}function Jf(e){if(!Xf(e))return[];let t=Zf(e,`id`),n=Zf(e,`path`),r=Zf(e,`cwd`),i=Zf(e,`created`),a=Zf(e,`modified`),o=Zf(e,`firstMessage`),s=$f(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=Qf(e,`name`),l=Qf(e,`parentSessionPath`),u=Qf(e,`machineId`)??Rf,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 Yf(e){return Lf in e}function Xf(e){return typeof e==`object`&&!!e}function Zf(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Qf(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function $f(e,t){let n=e[t];return typeof n==`number`?n:void 0}function ep(e){return yp(e.flatMap(ap)).filter(e=>e.parts.length>0)}function tp(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function np(e,t){let n=dp(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=Op(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 rp(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,tp(t,n)]}function ip(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 ap(e){if(sp(e))return[e];if(z(e,`role`)===`bashExecution`)return[np(mp(e),e)];let t=hp(z(e,`role`)),n=gp(Dp(e,`content`),e),r=t===`user`?cp(n):void 0;if(r!==void 0)return r.map(t=>np(t,e));let i=up(e);if(t===`tool`)return[np({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?[np({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=op(e);return c===void 0?s:[...s,np(c,e)]}function op(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return tp(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function sp(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Dp(e,`parts`))}function cp(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=lp(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 lp(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 up(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function dp(e){let t=fp(Dp(e,`timestamp`)),n=pp(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function fp(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 pp(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 mp(e){let t=z(e,`command`)??``,n=Op(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Dp(e,`output`);r!=null&&n.push(``,Ap(r));let i=Dp(e,`exitCode`);i!=null&&n.push(``,`exit ${Ap(i)}`),Op(e,`cancelled`)===!0&&n.push(``,`cancelled`),Op(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(`
5
5
  `)}]}}function hp(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function gp(e,t){return typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=z(e,`type`),n=z(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=z(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=z(e,`name`)??`tool`,n=Dp(e,`arguments`),r=z(e,`id`),i=t===`read`?vp(z(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:wp(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=z(e,`data`),n=z(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return Cp(e)}).map(e=>e.type===`text`&&z(t,`role`)===`toolResult`?_p(e.text,t):e):Cp(e)}function _p(e,t){let n=z(t,`toolCallId`),r=Dp(t,`content`),i=Dp(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:z(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:Op(t,`isError`)===!0}}function vp(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(!(n===void 0||n===``))return{name:n,path:e}}function yp(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.entryId===void 0?{}:{entryId:r.entryId},...r.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:r.previousAssistantEntryId},...r.canFork===void 0?{}:{canFork:r.canFork},...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts){if(o.type===`toolCall`){a();let e=bp(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0});continue}if(o.type===`toolResult`){let e=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(e!==void 0&&xp(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function bp(e){return{type:`toolExecution`,...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:`pending`}}function xp(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=Sp(n.details)??i.preview,o={...i,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...a===void 0?{}:{preview:a}};return e[t.lineIndex]={...r,parts:[...r.parts.slice(0,t.partIndex),o,...r.parts.slice(t.partIndex+1)]},!0}function Sp(e){let t=Dp(e,`preview`);if(!Ep(t))return;let n=z(t,`diff`),r=z(t,`error`),i=kp(t,`firstChangedLine`);if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function Cp(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:wp(e)}]:[{type:`text`,text:Ap(e)}]}function wp(e){if(!Ep(e))return Ap(e);let t=z(e,`command`);if(t!==void 0)return t;let n=z(e,`path`);if(n!==void 0)return n;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return`edit text replacement`;let r=e.edits;return Array.isArray(r)?`${String(r.length)} edit${r.length===1?``:`s`}`:Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,t])=>`${e}: ${Tp(t)}`).join(` · `)}function Tp(e){return typeof e==`string`?e.length>80?`${e.slice(0,77)}…`:e:typeof e==`number`||typeof e==`boolean`?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?``:`s`}`:typeof e==`object`&&e?`object`:``}function Ep(e){return typeof e==`object`&&!!e}function Dp(e,t){return Ep(e)?e[t]:void 0}function z(e,t){let n=Dp(e,t);return typeof n==`string`?n:void 0}function Op(e,t){let n=Dp(e,t);return typeof n==`boolean`?n:void 0}function kp(e,t){let n=Dp(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ap(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var jp=new class{constructor(){this.scopes=new Map,this.migratedScopes=new Map,this.attachmentSeq=0}read(e){let t=this.scopes.get(e);return t===void 0?{attachments:[]}:this.readScope(t)}write(e,t){let n=this.findScopeState(e)??this.createScopeState(e);this.writeScope(n,t)}openScope(e){return this.scopeHandle(this.findScopeState(e)??this.createScopeState(e))}findScope(e){let t=this.findScopeState(e);return t===void 0?void 0:this.scopeHandle(t)}clear(e){let t=this.findScopeState(e);t!==void 0&&this.invalidateScope(t)}move(e,t){if(e===t){let t=this.findScopeState(e);t!==void 0&&(t.draft=void 0);return}let n=this.findScopeState(e),r=this.findScopeState(t);if(n===void 0){r!==void 0&&this.invalidateScope(r);return}r!==void 0&&r!==n&&this.invalidateScope(r),this.removeCanonicalMapping(n),n.currentKey=t,n.valid=!0,this.scopes.set(t,n),this.migratedScopes.set(e,n)}nextAttachmentId(){return this.attachmentSeq+=1,`attachment-${String(this.attachmentSeq)}`}hasEntry(e){return this.scopes.get(e)?.draft!==void 0}createScopeState(e){let t={currentKey:e,valid:!0,draft:void 0};return this.scopes.set(e,t),this.migratedScopes.delete(e),t}findScopeState(e){let t=this.scopes.get(e);if(t!==void 0)return t.valid?t:void 0;let n=this.migratedScopes.get(e);if(n!==void 0){if(!n.valid){this.migratedScopes.delete(e);return}return n}}scopeHandle(e){return{currentKey:()=>e.valid?e.currentKey:void 0,read:()=>this.readScope(e),write:t=>{this.writeScope(e,t)},clear:()=>{this.invalidateScope(e)},beginCapture:()=>({complete:(t,n)=>this.completeCapture(e,t,n)})}}readScope(e){return!e.valid||e.draft===void 0?{attachments:[]}:{attachments:[...e.draft.attachments],...e.draft.error===void 0?{}:{error:e.draft.error}}}writeScope(e,t){if(e.valid){if(t.attachments.length===0&&t.error===void 0){e.draft=void 0;return}e.draft={attachments:[...t.attachments],...t.error===void 0?{}:{error:t.error}}}}completeCapture(e,t,n){if(!e.valid)return;let r={attachments:[...e.draft?.attachments??[],...t.map(e=>({id:this.nextAttachmentId(),...e}))],...n===void 0?{}:{error:n}};return this.writeScope(e,r),this.readScope(e)}removeCanonicalMapping(e){for(let[t,n]of this.scopes)n===e&&this.scopes.delete(t)}invalidateScope(e){e.valid=!1,e.draft=void 0,this.removeCanonicalMapping(e);for(let[t,n]of this.migratedScopes)n===e&&this.migratedScopes.delete(t)}},Mp=`pi-webui:prompt-draft:`;function Np(e){return`${Mp}${e}`}function Pp(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Fp(e,t=Pp()){try{return t?.getItem(Np(e))??``}catch{return``}}function Ip(e,t,n=Pp()){try{t?n?.setItem(Np(e),t):n?.removeItem(Np(e))}catch{}}function Lp(e,t=Pp()){try{t?.removeItem(Np(e))}catch{}}function Rp(e,t,n=Pp()){let r=Fp(e,n);r!==``&&(Ip(t,r,n),Lp(e,n))}function zp(e,t){return tp(`bash`,`${t===!0?`excluded from context
6
6
 
7
7
  `:``}$ ${e}`)}function Bp(e,t){let n=e.at(-1),r=n?.parts.at(-1);if(n?.role!==`bash`||r?.type!==`text`)return[...e,tp(`bash`,t)];let i=Up(r.text)?``:`
@@ -19,7 +19,7 @@ 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
19
19
  `)}function mm(e,t){let n=ap(t);return n.length===0?e:[...e,...n]}function hm(e,t){let n=e.at(-1);return gm(e,t)?e:n?.role===t.role&&t.role!==`skill`?[...e.slice(0,-1),{...n,parts:[...n.parts,...t.parts]}]:[...e,t]}function gm(e,t){let n=cm(t);if(t.role!==`skill`||n.length===0)return!1;let r=vm(e)+1;return n.every(t=>_m(e,t,r))}function _m(e,t,n){for(let r=e.length-1;r>=n;r--)if(cm(e[r]).some(e=>um(e,t)))return!0;return!1}function vm(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role===`user`)return t;return-1}function ym(e){return typeof e==`object`&&!!e}function bm(e,t){return ym(e)?e[t]:void 0}function xm(e,t){let n=bm(e,t);return typeof n==`string`?n:void 0}function Sm(e,t){let n=bm(e,t);return typeof n==`boolean`?n:void 0}var Cm=`pi-webui:chat-history:v2:`,wm=1800*1e3;function Tm(e){try{let t=sessionStorage.getItem(Mm(e));if(t===null||t===``)return;let n=JSON.parse(t);if(!Nm(n))return;if(Date.now()-n.savedAt>wm){sessionStorage.removeItem(Mm(e));return}return{messages:n.messages,start:n.start,total:n.total}}catch{return}}function Em(e,t){try{sessionStorage.setItem(Mm(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Dm(e){try{sessionStorage.removeItem(Mm(e))}catch{}}function Om(e,t){if(e===void 0||!Pm(e))return t;if(!Pm(t))return e;if(km(e,t))return t;let n=Math.min(e.start,t.start),r=Math.max(e.start+e.messages.length,t.start+t.messages.length),i=Array(r-n);return jm(i,n,e),jm(i,n,t),Am(i)?t:{start:n,total:Math.max(e.total,t.total),messages:i}}function km(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Am(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function jm(e,t,n){n.messages.forEach((r,i)=>{e[n.start-t+i]=r})}function Mm(e){return`${Cm}${e}`}function Nm(e){if(typeof e!=`object`||!e||!(`messages`in e)||!(`start`in e)||!(`total`in e)||!(`savedAt`in e))return!1;let{messages:t,start:n,total:r,savedAt:i}=e;return Array.isArray(t)&&typeof n==`number`&&typeof r==`number`&&typeof i==`number`&&Pm({messages:t,start:n,total:r})}function Pm(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some(Fm)}function Fm(e){return typeof e==`object`&&!!e&&`role`in e&&`parts`in e&&!(`content`in e)&&typeof e.role==`string`&&Array.isArray(e.parts)}var Im=e=>{setTimeout(e,0)},Lm={read:Tm,write:Em,remove:Dm},Rm=class{constructor(e=Lm,t=Im){this.cache=e,this.scheduleWrite=t,this.rawHistoryPages=new Map,this.normalizedViews=new WeakMap,this.pendingWrites=new Set}cachedView(e){return this.viewFromHistory(this.rawHistoryPage(e))}mergeHistory(e,t){let n=Om(this.rawHistoryPage(e),t);return this.rawHistoryPages.set(e,n),this.queueCacheWrite(e),this.viewFromHistory(n)}applyLiveEvent(e,t){return Gp(e,t)}seedStreamingPartial(e,t){return Wp(e,t)}discard(e){this.rawHistoryPages.delete(e),this.pendingWrites.delete(e),this.cache.remove?.(e)}queueCacheWrite(e){this.pendingWrites.has(e)||(this.pendingWrites.add(e),this.scheduleWrite(()=>{this.flushCacheWrite(e)}))}flushCacheWrite(e){if(!this.pendingWrites.delete(e))return;let t=this.rawHistoryPages.get(e);t!==void 0&&this.cache.write(e,t)}rawHistoryPage(e){let t=this.rawHistoryPages.get(e)??this.cache.read(e);return t!==void 0&&this.rawHistoryPages.set(e,t),t}viewFromHistory(e){if(e===void 0)return zm(void 0);let t=this.normalizedViews.get(e);if(t!==void 0)return t;let n=zm(e);return this.normalizedViews.set(e,n),n}};function zm(e){let t=e?.start??0;return{messages:ep(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Bm(e,t=e.length){let n=e.slice(0,t),r=Hm(n,t);if(r!==void 0)return r;let i=Um(n,t);if(i!==void 0)return i;let a=Math.max(n.lastIndexOf(` `),n.lastIndexOf(`
20
20
  `))+1,o=n.slice(a);if(n.slice(0,a).endsWith(`@ `))return{kind:`file`,query:o,from:a-2,to:t,fileScope:`all`,allPrefix:`@ `};if(o.startsWith(`/`)&&a===0)return{kind:`command`,query:o.slice(1),from:a,to:t};if(o.startsWith(`!@`))return{kind:`file`,query:o.slice(2),from:a,to:t,fileScope:`all`,allPrefix:`!@`};if(o.startsWith(`@`))return{kind:`file`,query:o.slice(1),from:a,to:t,fileScope:`tracked`}}function Vm(e,t,n){let r=n??`@`;return!t&&!e.includes(` `)?`${r}${e}`:`${r}"${e}"`}function Hm(e,t){let n=e.lastIndexOf(`"`);if(n===-1)return;let r=e.slice(0,n);if(r.endsWith(`!@`))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`!@`,quoted:!0};if(r.endsWith(`@`))return{kind:`file`,query:e.slice(n+1),from:r.length-1,to:t,fileScope:`tracked`,quoted:!0};if(r.endsWith(`@ `))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`@ `,quoted:!0}}function Um(e,t){let n=e.lastIndexOf(`
21
21
  `)+1,r=e.slice(n),i=Wm(r,`@ `),a=Wm(r,`!@`),o=Math.max(i,a);if(o===-1)return;let s=o===a?`!@`:`@ `,c=n+o,l=c+s.length;return{kind:`file`,query:e.slice(l),from:c,to:t,fileScope:`all`,allPrefix:s}}function Wm(e,t){for(let n=e.lastIndexOf(t);n>=0;n=e.lastIndexOf(t,n-1))if(n===0||Gm(e[n-1]))return n;return-1}function Gm(e){return e===` `||e===` `}function Km(e){let t=e.trimStart();return t.startsWith(`!@`)?{kind:`file`}:t.startsWith(`!`)?{kind:`shell`,excludeFromContext:t.startsWith(`!!`)}:Ym(e).startsWith(`/`)?{kind:`command`}:Bm(e)?.kind===`file`?{kind:`file`}:{kind:`normal`}}function qm(e){return Km(e).kind===`shell`}function Jm(e,t){return e.kind===t.kind?e.kind===`shell`&&t.kind===`shell`?e.excludeFromContext===t.excludeFromContext:!0:!1}function Ym(e){let t=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`
22
- `))+1;return e.slice(t)}var Xm=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),sh(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=Rc(e,this.machineId);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){let r=Qm(await oh(e));this.socket!==t||r===void 0||r.type===`notifications.inbox`&&(n.id!==r.summary.sessionId||n.cwd!==r.summary.cwd)||this.onEvent?.(r)}},Zm=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),sh(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=Bc(this.machineId);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){let n=$m(await oh(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function Qm(e){return ah(e)===`notifications.inbox`?rh(()=>Kr(e)):eh(e)?e:void 0}function $m(e){if(ah(e)===`sessions.unread`)return ih(()=>zr(e));if(th(e)||nh(e))return e}function eh(e){return[`message.append`,`assistant.delta`,`assistant.thinking.delta`,`tool.start`,`tool.update`,`tool.end`,`shell.start`,`shell.chunk`,`shell.end`,`agent.start`,`agent.end`,`message.end`,`status.update`,`activity.update`,`command.output`,`session.extensionEntry`,`session.subscribed`,`session.error`,`session.name`,`session.created`,`pi.event`].includes(ah(e))}function th(e){let t=ah(e);return t===`status.update`||t===`activity.update`||t===`session.name`||t===`session.created`}function nh(e){let t=ah(e);return t===`terminal.created`||t===`terminal.exited`||t===`terminal.closed`||t===`workspace.activity`}function rh(e){return ih(e)}function ih(e){try{return e()}catch{return}}function ah(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function oh(e){try{return typeof e==`string`?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function sh(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}var ch=new TextEncoder;function lh(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`||e.type===`tool.update`}var uh=class{constructor(e={}){this.runs=[],this.toolUpdateRuns=new Map,this.pendingByteCount=0,this.resyncRequired=!1,this.maxEventRuns=e.maxEventRuns??128,this.maxBytes=e.maxBytes??262144,this.maxToolUpdateKeys=e.maxToolUpdateKeys??64}get eventCount(){return this.runs.length+this.toolUpdateRuns.size}get pendingBytes(){return this.pendingByteCount}enqueue(e){if(!(this.resyncRequired||!lh(e))){if(e.type===`tool.update`){this.enqueueToolUpdate(e);return}this.enqueueAccumulating(e)}}enqueueToolUpdate(e){let t=this.toolUpdateRuns.get(e.toolCallId);if(t!==void 0){t.latest=gh(e),t.seq=vh(t.seq,e.seq);return}if(this.toolUpdateRuns.size+1>this.maxToolUpdateKeys){this.markResyncRequired();return}this.toolUpdateRuns.set(e.toolCallId,{type:`tool.update`,toolCallId:e.toolCallId,latest:gh(e),seq:e.seq})}enqueueAccumulating(e){let t=this.runs.at(-1),n=t!==void 0&&dh(t,e),r=this.runs.length+ +!n,i=n?ph(t,e):yh(e),a=n?t.bytes:0,o=this.pendingByteCount-a+i;if(r>this.maxEventRuns||o>this.maxBytes){this.markResyncRequired();return}if(n){mh(t,e,i),this.pendingByteCount=o;return}this.runs.push(fh(e,i)),this.pendingByteCount=o}drain(){if(this.resyncRequired)return this.resyncRequired=!1,{events:[],resyncRequired:!0};let e=[];for(let t of this.runs)e.push(hh(t));for(let t of this.toolUpdateRuns.values())e.push(_h(t.latest,t.seq));return this.reset(),{events:e,resyncRequired:!1}}clear(){this.reset(),this.resyncRequired=!1}reset(){this.runs=[],this.toolUpdateRuns.clear(),this.pendingByteCount=0}markResyncRequired(){this.reset(),this.resyncRequired=!0}};function dh(e,t){switch(e.type){case`assistant.delta`:return t.type===`assistant.delta`;case`assistant.thinking.delta`:return t.type===`assistant.thinking.delta`;case`shell.chunk`:return t.type===`shell.chunk`}}function fh(e,t){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`?{type:e.type,chunks:[e.text],seq:e.seq,bytes:t}:{type:e.type,chunks:[e.chunk],seq:e.seq,bytes:t}}function ph(e,t){return e.bytes+yh(t)}function mh(e,t,n){if(e.type===`assistant.delta`&&t.type===`assistant.delta`){e.chunks.push(t.text),e.seq=vh(e.seq,t.seq),e.bytes=n;return}if(e.type===`assistant.thinking.delta`&&t.type===`assistant.thinking.delta`){e.chunks.push(t.text),e.seq=vh(e.seq,t.seq),e.bytes=n;return}e.type===`shell.chunk`&&t.type===`shell.chunk`&&(e.chunks.push(t.chunk),e.seq=vh(e.seq,t.seq),e.bytes=n)}function hh(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`?_h({type:e.type,text:e.chunks.join(``)},e.seq):_h({type:e.type,chunk:e.chunks.join(``)},e.seq)}function gh(e){return{type:e.type,toolName:e.toolName,toolCallId:e.toolCallId,text:e.text,...e.content===void 0?{}:{content:e.content},...e.details===void 0?{}:{details:e.details}}}function _h(e,t){return t===void 0?e:{...e,seq:t}}function vh(e,t){return e===void 0?t:t===void 0?e:Math.max(e,t)}function yh(e){return ch.encode(JSON.stringify(e)).byteLength}function bh(e){return e?.ok===!0&&E(e,w.sessionsPersistedState)}function xh(e){return{authoritative:bh(e)}}function Sh(e,t,n={}){if(e===void 0)return`unknown`;let r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?`persisted`:r===!1||Wf(e)?`transient`:n.authoritative===!0?`unknown`:`persisted`}function Ch(e,t,n){return e!==void 0&&e.archived!==!0&&Sh(e,t,n)===`persisted`}function wh(e,t,n){return e!==void 0&&e.archived!==!0&&Sh(e,t,n)===`transient`}function Th(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Eh=class{constructor(e,t,n=Th()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Oh(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 Dh(e){return typeof e==`string`&&e!==``?e:void 0}function Oh(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!kh(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 kh(e){return!Ah(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 Ah(e){return typeof e==`object`&&!!e}var jh=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},Mh=`pi-webui:session-selection:v1`,Nh=class{constructor(e=Th()){this.sessionIdsByCwd=new Eh(Mh,Dh,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function Ph(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return Ih(e,n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function Fh(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function Ih(e,t){return e.find(e=>e.id===t||e.id.startsWith(t))}function Lh(e,t,n){return Rh(e,[t],n)}function Rh(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function zh(e,t,n){return Bh(e,t,[n])}function Bh(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}var Vh=class{get signal(){return this.controller?.signal}restart(){this.abort();let e=new AbortController;return this.controller=e,e.signal}abort(){let e=this.controller;e!==void 0&&(this.controller=void 0,e.abort(new Hh))}},Hh=class extends Error{constructor(){super(`Load cancelled because the selection changed`),this.name=`LoadCancelledError`}};function Uh(e){return e instanceof Hh||Wh(e)&&e.name===`AbortError`}function Wh(e){return typeof e==`object`&&!!e&&`name`in e}var Gh=100,Kh=1e3,qh=4,Jh=512,Yh=(e,t)=>{let n=globalThis.setTimeout(e,t);return()=>{globalThis.clearTimeout(n)}};function Xh(e,t){let n=t.entryId===``?-1:e.findIndex(e=>e.entryId===t.entryId),r=n===-1?[...e,t]:e.map((e,r)=>r===n?t:e);return r.length>200?r.slice(r.length-200):r}var Zh=class{constructor(e){this.maxEvents=e,this.events=[],this.overflow=!1}get overflowed(){return this.overflow}push(e){if(!this.overflow){if(this.events.length>=this.maxEvents){this.events=[],this.overflow=!0;return}this.events.push(e)}}drain(){let e=this.events;return this.events=[],e}},Qh=class{constructor(e,t,n,r=new jh,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectionSeq=0,this.extensionStreamGeneration=0,this.sessionReorderInFlight=!1,this.disposed=!1,this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.modelPolicyIssueSeq=0,this.modelPolicyLoadSeq=0,this.modelPolicySaveSeq=0,this.modelPolicySettledSaveSeq=0,this.modelPolicySavesInFlight=new Set,this.pendingSessionStarts=new Map,this.starterModelPolicySubstitutionChecks=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new Sd,this.selectionLoad=new Vh,this.socket=i.socket??new Xm,this.api=i.api??Lc,this.attachmentDrafts=i.attachmentDrafts??jp,this.transcripts=i.transcripts??new Rm,this.streamEventBuffer=i.streamEventBuffer??new uh,this.now=i.now??(()=>Date.now()),this.scheduleOverloadResync=i.scheduleOverloadResync??Yh,this.maxJoinBufferedEvents=i.maxJoinBufferedEvents??Jh,this.notifications=i.notifications,this.replacePromptEditorText=i.replacePromptEditorText,this.onSelectedSessionReady=i.onSelectedSessionReady,this.onStarterModelPolicyConfirmed=i.onStarterModelPolicyConfirmed,this.onStarterModelPolicySubstitution=i.onStarterModelPolicySubstitution,this.refreshProjectSessionCatalog=i.refreshProjectSessionCatalog??(()=>void 0)}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}dispose(){this.disposed=!0,this.selectionSeq+=1,this.selectionLoad.abort(),this.socket.close(),this.clearPendingUpdates(),this.starterModelPolicySubstitutionChecks.clear()}clearActiveSession(){this.selectionSeq+=1,this.selectionLoad.abort(),this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.resetExtensionBaseline(),this.clearPendingUpdates(),this.resetExtensionBaseline(),this.setState({selectedSession:void 0,messages:[],sessionExtensionEntries:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,availableThinkingLevels:[],...this.clearSelectedModelPolicyState(),treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){let e=this.getState();Fh(e.sessions,e.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(e){return this.startSessionRequest({kind:`legacy`,...e===void 0?{}:{modelPolicy:e}})}async startPlusSession(e){return this.startSessionRequest({kind:`plus`,initialModelPolicy:e})}async startSessionRequest(e){let t=this.getState().selectedWorkspace;if(!t)return!1;let n=R(this.getState()),r=this.createPendingSessionStart(t,n,e);this.pendingSessionStarts.set(r.tempId,r);try{this.insertAndSelectPendingSession(r.session)}catch(e){throw this.failPendingSessionStart(r.tempId,e),e}try{let e=r.request.kind===`plus`?await this.api.startPlusSession(t.path,r.request.initialModelPolicy,n):await this.api.startSession(t.path,n,r.request.modelPolicy);return await this.resolvePendingSessionStart(r.tempId,e),!r.discarded&&r.request.kind===`plus`&&e.creationSource===`session-list-plus`&&this.publishStarterModelPolicyConfirmed({reason:`creation`,machineId:n,session:{...e},requestedPolicy:r.request.initialModelPolicy}),!0}catch(e){return this.failPendingSessionStart(r.tempId,e),!1}}async startSessionWithPrompt(e,t,n,r=`inline`,i,a){return this.startSessionWithPromptRequest(e,t,n,r,{kind:`legacy`,...i===void 0?{}:{modelPolicy:i}},a)}async startPlusSessionWithPrompt(e,t,n,r,i,a){return this.startSessionWithPromptRequest(e,t,n,r,{kind:`plus`,initialModelPolicy:i},a)}async startSessionWithPromptRequest(e,t,n,r,i,a){let o=this.startSessionRequest(i).then(e=>({rejected:!1,started:e}),e=>({rejected:!0,started:!1,error:e})),s;try{s=await this.send(e,t,n,r,!0)}finally{a?.((await o).started)}let c=await o;if(c.rejected)throw c.error;return c.started&&s}preferredSession(e,t,n){return Ph(t,{targetSessionId:n,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e))})}async selectSession(e,t){if(this.disposed)return;if(cg(e)){this.selectClientPendingStartSession(e,t);return}this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let n=++this.selectionSeq;this.selectionLoad.restart(),this.socket.close(),this.streamWatermark=void 0,this.resetExtensionBaseline(),this.clearPendingUpdates();let r=R(this.getState());this.notifications?.prepareSelectedSession(e,r);let i=this.sessionCacheKey(e.id),a=this.transcripts.cachedView(i);this.setState({selectedSession:e,...a,sessionExtensionEntries:[],isLoadingEarlierMessages:!1,...t?.preserveTreeDialog===!0?{}:{treeDialog:void 0},status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],availableThinkingLevels:[],...this.clearSelectedModelPolicyState()});let o;try{if(e.archived===!0){let a=await this.api.messages(e,{limit:Gh},R(this.getState()),this.selectionLoad.signal);if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let o=this.transcripts.mergeHistory(i,a);this.setState({...o,isLoadingEarlierMessages:!1,status:void 0,activity:void 0}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl();return}let a={session:e,machineId:r,selectionSeq:n},s=new Zh(this.maxJoinBufferedEvents);if(o=s,this.socket.connect(e,e=>{s.push(e)},()=>{this.resetExtensionBaseline(),this.refreshSelectedSession(e.id)},r,()=>{this.notifications?.refreshSelectedSession(e,r)}),await this.requestSelectedSessionRefresh(a),!this.isCurrentRefreshTarget(a))return;this.refreshAvailableThinkingLevels(),this.applyJoinBufferedEvents(s,a),this.socket.setHandler(e=>{this.applyEvent(e)}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(i){if(Uh(i))return;if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(t?.propagateRefreshError===!0&&this.isSelectedSessionIdentity(e.id,r))throw i;return}if(Wf(e)&&Dg(i)){await this.recreateCachedNewSession(e,t);return}if(o!==void 0){if(!o.overflowed)for(let e of o.drain())this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)})}if(this.setState({error:String(i)}),t?.propagateRefreshError===!0)throw i}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)return;let n=R(e),r=this.selectionSeq,i=this.selectionLoad.signal;this.setState({isLoadingEarlierMessages:!0});try{let a=await this.api.messages(t,{before:e.messagePageStart,limit:Gh},n,i);if(!this.isCurrentHistoryTarget(t.id,n,r))return;let o=this.transcripts.mergeHistory(this.sessionCacheKey(t.id),a);this.setState(o)}catch(e){!Uh(e)&&this.isCurrentHistoryTarget(t.id,n,r)&&this.setState({error:String(e)})}finally{this.isCurrentHistoryTarget(t.id,n,r)&&this.setState({isLoadingEarlierMessages:!1})}}async send(e,t,n,r=`inline`,i=!1){return await this.sendWithPendingOutcome(e,t,n,r,i)}async sendWithPendingOutcome(e,t,n,r,i){let a=this.getState().selectedSession;if(!a||a.archived===!0)return!1;let o=e.trim(),s=n!==void 0&&n.length>0;if(cg(a)){let c=!s&&o.startsWith(`/`)?{type:`command`,text:e}:!s&&qm(e)?{type:`shell`,text:e}:{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r};return i?await new Promise(e=>{this.enqueuePendingSessionSend(a,c,e)||e(!1)}):this.enqueuePendingSessionSend(a,c)}return!s&&o.startsWith(`/`)?this.runCommand(e):!s&&qm(e)?this.runShell(e):await this.deliverPromptToSession(a,e,t,n,r,R(this.getState()),{markSending:s})}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:rg(n,e)})}async runShell(e){let t=this.getState().selectedSession;return!t||t.archived===!0?!1:cg(t)?this.enqueuePendingSessionSend(t,{type:`shell`,text:e}):await this.deliverShellToSession(t,e,R(this.getState()),{optimisticLine:!0})}async runCommand(e){let t=this.getState().selectedSession;return!t||t.archived===!0?!1:cg(t)?this.enqueuePendingSessionSend(t,{type:`command`,text:e}):await this.deliverCommandToSession(t,e,R(this.getState()),{applyResult:!0})}async renameSession(e,t){if(e.archived===!0||cg(e))return;let n=t.trim();if(n===``)return;let r=R(this.getState());try{let t=await this.api.runCommand(e,`/name ${n}`,r);if(R(this.getState())!==r)return;if(t.type===`done`&&t.session!==void 0){this.applySessionName(t.session.id,t.session.name);return}this.setState({error:t.type===`unsupported`?t.message:`Could not rename session.`})}catch(e){R(this.getState())===r&&this.setState({error:String(e)})}}enqueuePendingSessionSend(e,t,n){let r=this.pendingSessionStarts.get(e.id);if(r===void 0||r.discarded)return this.setState({error:`The backend session is not ready for queued sends. Copy your message before discarding this failed start.`}),!1;let i={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`,...n===void 0?{}:{onDelivered:n}};r.queuedSends.push(i);let a=this.getState(),o=a.clientQueuedSessionMessages[e.id]??[],s=lg(e.id,r.queuedSends.length);return this.setState({clientQueuedSessionMessages:{...a.clientQueuedSessionMessages,[e.id]:[...o,dg(i)]},sessionActivities:{...a.sessionActivities,[e.id]:s},activity:a.selectedSession?.id===e.id?s:a.activity,error:``}),!0}async flushQueuedPendingSends(e,t,n){for(let r=0;r<n.length;r+=1){let i=n[r];if(i===void 0)continue;let a=await this.deliverQueuedPendingSend(e,t,i);if(i.onDelivered?.(a),!a){for(let e of n.slice(r+1))e.onDelivered?.(!1);return}this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,t,{markSending:!0}):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0}):this.deliverCommandToSession(e,n.text,t,{applyResult:!0})}async deliverPromptToSession(e,t,n,r,i,a,o){let s=r!==void 0&&r.length>0;o.markSending&&this.markSendingPrompt(e.id,!0);try{if(s&&i===`folder`){let i=(await this.api.saveAttachments(e,r,a)).map(e=>Vm(e.path,!1)).join(` `),o=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,o,n,a)}else await this.api.prompt(e,t,n,a,r);return this.markCachedNewSessionPersisted(e),!0}catch(e){return this.setState({error:String(e)}),!1}finally{o.markSending&&this.markSendingPrompt(e.id,!1)}}async deliverShellToSession(e,t,n,r){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,tp(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,tp(`system`,String(t))]}),this.setState({error:String(t)}),!1}}async deliverCommandToSession(e,t,n,r){this.markSendingPrompt(e.id,!0);try{let i=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?this.applyCommandResult(i):(i.type===`select`||i.type===`tree`)&&this.setState({error:`Queued command “${t}” needs input; open the session and run it again.`}),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,tp(`system`,String(t))]}),this.setState({error:String(t)}),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?rg(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(n){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(n,e,t,R(this.getState())))}catch(e){this.setState({error:String(e)})}}}cancelCommand(){this.setState({commandDialog:void 0})}async navigateTree(e,t){let n=this.getState(),r=n.selectedSession,i=n.treeDialog;if(r===void 0||i===void 0||r.archived===!0||cg(r))throw Error(`The session tree navigator is no longer available`);let a=R(n),o=this.selectionSeq,s;try{s=await this.api.navigateTree(r,{targetId:e,expectedLeafId:i.activeLeafId,summary:t},a)}catch(e){throw this.isCurrentSessionSelection(r.id,a,o)&&this.setState({error:String(e)}),e}return s.cancelled||await this.refreshAfterTreeNavigation(r,a,s.editorText??``,i),s}async editFromHere(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||cg(r))throw Error(`The message action is no longer available`);let i=R(n),a=this.selectionSeq,o;try{o=await this.api.editFromHere(r,e,i)}catch(e){throw this.isCurrentSessionSelection(r.id,i,a)&&this.setState({error:String(e)}),e}return o.cancelled||await this.refreshAfterTreeNavigation(r,i,t),o}async forkFromHere(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||n.archived===!0||cg(n))return;let r=R(t),i=this.selectionSeq,a;try{a=await this.api.forkFromHere(n,e,r)}catch(e){this.isCurrentSessionSelection(n.id,r,i)&&this.setState({error:String(e)});return}if(a.cancelled)return;let o=this.getState();if(R(o)!==r)return;let s=[a.session,...o.sessions.filter(e=>e.id!==a.session.id)];this.setState({sessions:s}),this.isCurrentSessionSelection(n.id,r,i)&&await this.selectSession(a.session)}async refreshAfterTreeNavigation(e,t,n,r){let i=xd(t,e.id);if(Ip(i,n),this.transcripts.discard(i),!this.isSelectedSessionIdentity(e.id,t))return;this.clearPendingUpdates();let a;try{await this.selectSession(e,{updateUrl:!1,...r===void 0?{}:{preserveTreeDialog:!0},propagateRefreshError:!0})}catch(e){a={error:e}}if(this.isSelectedSessionIdentity(e.id,t)){try{await this.replacePromptEditorText?.({machineId:t,sessionId:e.id,text:n})}catch(n){throw this.isSelectedSessionIdentity(e.id,t)&&this.setState({error:String(n)}),n}if(a!==void 0)throw this.isSelectedSessionIdentity(e.id,t)&&this.setState({error:String(a.error)}),a.error;r!==void 0&&this.isSelectedSessionIdentity(e.id,t)&&this.getState().treeDialog===r&&this.setState({treeDialog:void 0})}}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||cg(t))return;let n=R(e),r=this.selectionSeq;try{await this.api.abort(t,n)}catch(e){throw this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)}),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e),n=this.sessionPersistenceOptions();if(wh(e,t,n)){await this.deleteCachedNewSession(e);return}if(Ch(e,t,n))try{await this.api.archive(e,R(this.getState()));let t=this.getState(),n=Lh(t.sessions,e.id,new Date().toISOString()),r=zh(n,t.selectedSession?.id,e.id);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(!(e===void 0||!Ch(e,this.statusForSession(e),this.sessionPersistenceOptions())))try{let t=await this.api.archiveWithDescendants(e,R(this.getState())),n=t.sessionIds!==void 0&&t.sessionIds.length>0?t.sessionIds:[e.id],r=this.getState(),i=Rh(r.sessions,n,new Date().toISOString()),a=Bh(i,r.selectedSession?.id,n);this.setState({sessions:i}),a.type===`select`?await this.selectSession(a.session):a.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessions(e){let t=this.sessionPersistenceOptions(),n=mg(e).filter(e=>Ch(e,this.statusForSession(e),t));if(n.length!==0)try{let e=R(this.getState()),{succeededIds:t,failures:r,generatedAt:i}=await this.archiveSessionBatch(n,e);if(t.length>0){let e=this.getState(),n=Rh(e.sessions,t,i??new Date().toISOString()),r=Bh(n,e.selectedSession?.id,t);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures(`Archive`,r)}catch(e){this.setState({error:`Archive failed: ${xg(e)}`})}}async deleteArchivedSessions(e){let t=mg(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=R(this.getState()),r=this.getState().machineRuntimes[n];if(r?.ok===!0&&!E(r,w.sessionsDeleteArchived)){this.setState({error:`Deleting archived sessions requires an updated Pi-Web runtime on this machine.`});return}try{let{succeededIds:e,failures:r}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let t=new Set(e),n=this.getState(),r=n.sessions.filter(e=>!t.has(e.id));if(this.setState({sessions:r}),n.selectedSession!==void 0&&t.has(n.selectedSession.id)){let e=r.find(e=>e.archived!==!0)??r[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}}this.applyBulkSessionFailures(`Delete`,r)}catch(e){this.setState({error:`Delete failed: ${xg(e)}`})}}async archiveSessionBatch(e,t){let n=this.getState().machineRuntimes[t];if(n?.ok===!0&&E(n,w.sessionsBulkMutations)){let n=await this.api.archiveMany(e,t);return{succeededIds:n.archivedSessionIds,failures:gg(n.failures),generatedAt:n.generatedAt}}let r=await vg(e,qh,async e=>(await this.api.archive(e,t),e.id));return{succeededIds:hg(r),failures:_g(e,r)}}async deleteArchivedSessionBatch(e,t){let n=this.getState().machineRuntimes[t];if(n?.ok===!0&&E(n,w.sessionsBulkMutations)){let n=await this.api.deleteArchivedMany(e,t);return{succeededIds:n.deletedSessionIds,failures:gg(n.failures)}}let r=await vg(e,qh,async e=>(await this.api.deleteArchived(e,t),e.id));return{succeededIds:hg(r),failures:_g(e,r)}}async applySessionCleanupResult(e,t=R(this.getState())){if(R(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=Rh(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);if(this.setState({sessions:o,sessionStatuses:ig(t.sessionStatuses,a),sessionActivities:ig(t.sessionActivities,a),...s?{status:void 0,activity:void 0}:{}}),t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=o.find(e=>e.archived!==!0)??o[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}else{let e=Bh(o,t.selectedSession?.id,n);e.type===`select`?await this.selectSession(e.session):e.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(t)}async refreshCurrentWorkspaceSessions(e=R(this.getState())){let t=this.getState().selectedWorkspace;if(t!==void 0)try{let n=Uf(t.path,await this.api.sessions(t.path,e),e).filter(t=>!this.isSuppressedCreatedSession(t,e));if(R(this.getState())!==e||this.getState().selectedWorkspace?.id!==t.id)return;let r=this.mergePendingStartSessions(t.path,n,e),i=this.getState().selectedSession;if(this.setState({sessions:r}),i===void 0)return;let a=r.find(e=>e.id===i.id);if(a!==void 0){a!==i&&this.setState({selectedSession:a});return}let o=r.find(e=>e.archived!==!0)??r[0];o===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(o)}catch(n){R(this.getState())===e&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(n)})}}async reorderSession(e,t){if(this.sessionReorderInFlight||e.archived===!0||e.persisted!==!0)return;let n=this.getState(),r=R(n),i=n.selectedWorkspace?.id,a=this.selectionSeq,o=t.orderedSessions.map((e,t)=>({...e,manualOrder:t})),s=Cg(n.sessions,t.orderedSessions),c=Cg(n.projectSessions,t.orderedSessions),l=Cg(n.selectedSession===void 0?[]:[n.selectedSession],t.orderedSessions);this.sessionReorderInFlight=!0,this.setState({sessions:Sg(n.sessions,o),projectSessions:Sg(n.projectSessions,o),selectedSession:n.selectedSession===void 0?void 0:Sg([n.selectedSession],o)[0]});try{let n=await this.api.reorder(e,t,r);if(!this.isCurrentSessionOrderScope(r,i,a))return;let o=this.getState();this.setState({sessions:Sg(o.sessions,n.orderedSessions),projectSessions:Sg(o.projectSessions,n.orderedSessions),selectedSession:o.selectedSession===void 0?void 0:Sg([o.selectedSession],n.orderedSessions)[0]})}catch(e){if(!this.isCurrentSessionOrderScope(r,i,a))return;let t=this.getState();this.setState({sessions:wg(t.sessions,s),projectSessions:wg(t.projectSessions,c),selectedSession:t.selectedSession===void 0?void 0:wg([t.selectedSession],l)[0],error:`Reorder failed: ${xg(e)}`}),await Promise.allSettled([this.refreshCurrentWorkspaceSessions(r),Promise.resolve().then(()=>this.refreshProjectSessionCatalog())])}finally{this.sessionReorderInFlight=!1}}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!wh(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=cg(e)?this.pendingSessionStarts.get(e.id):void 0;if(t!==void 0){t.discarded=!0;for(let e of t.queuedSends)e.onDelivered?.(!1);t.queuedSends=[]}else this.api.stop(e,R(this.getState())).catch(()=>{});Hf(e.id,R(this.getState())),Lp(this.sessionCacheKey(e.id)),this.attachmentDrafts.clear(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:rg(n.sessionStatuses,e.id),sessionActivities:$h(n.sessionActivities,e.id),sendingPrompts:rg(n.sendingPrompts,e.id),clientQueuedSessionMessages:rg(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=r.find(e=>e.archived!==!0)??r[0];i===void 0?(this.clearActiveSession(),this.updateUrl()):await this.selectSession(i)}async restoreSession(e=this.getState().selectedSession){if(e)try{await this.api.restore(e,R(this.getState()));let t={...e};delete t.archived,delete t.archivedAt,this.replaceSession(t),this.getState().selectedSession?.id===t.id&&await this.selectSession(t)}catch(e){this.setState({error:String(e)})}}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!Ch(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=R(this.getState()),n=this.getState().machineRuntimes[t];if(n?.ok!==!0||!E(n,w.sessionsReload)){this.setState({error:`Reloading sessions from disk requires an updated Pi-Web runtime on this machine.`});return}try{await this.api.reloadSession(e.id,t),this.transcripts.discard(this.sessionCacheKey(e.id)),this.getState().selectedSession?.id===e.id&&await this.selectSession(e,{updateUrl:!1})}catch(e){this.setState({error:String(e)})}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath!==void 0)try{await this.api.detachParent(e,R(this.getState()));let t={...e};delete t.parentSessionPath,delete t.manualOrder,this.replaceSession(t)}catch(e){this.setState({error:String(e)})}}async pinSession(e=this.getState().selectedSession){if(!(!e||e.archived===!0))try{let t=await this.api.pin(e,R(this.getState()));this.replaceSession(t)}catch(e){this.setState({error:String(e)})}}async unpinSession(e=this.getState().selectedSession){if(!(!e||e.archived===!0))try{let t=await this.api.unpin(e,R(this.getState()));this.replaceSession(t)}catch(e){this.setState({error:String(e)})}}async loadModelPolicy(){let e=this.selectedModelPolicyTarget();if(e===void 0)return;let{session:t,machineId:n,selectionSeq:r}=e,i=++this.modelPolicyIssueSeq;this.modelPolicyLoadSeq=i;let a=this.modelPolicySettledSaveSeq;this.modelPolicySavesInFlight.size>0?this.setState({isLoadingModelPolicy:!0}):this.setState({modelPolicy:void 0,modelPolicyError:void 0,isLoadingModelPolicy:!0});try{let e=await this.api.modelPolicy(t,n);this.canWriteModelPolicyReadResult(t.id,n,r,i,a)&&this.applyConfirmedModelPolicyResponse(e)}catch(e){this.canWriteModelPolicyReadResult(t.id,n,r,i,a)&&this.setState({modelPolicyError:String(e)})}finally{!this.disposed&&this.modelPolicyLoadSeq===i&&this.setState({isLoadingModelPolicy:!1})}}async saveModelPolicy(e){let t=this.selectedModelPolicyTarget();if(t===void 0)return;let{session:n,sessionInfo:r,machineId:i,selectionSeq:a}=t,o=++this.modelPolicyIssueSeq;this.modelPolicySaveSeq=o,this.modelPolicySavesInFlight.add(o),this.setState({modelPolicyError:void 0,isSavingModelPolicy:!0});try{let t=await this.api.setModelPolicy(n,e,i);this.canWriteModelPolicyWriteResult(n.id,i,a,o)&&(this.applyConfirmedModelPolicyResponse(t),tg(r)&&t.policy!==void 0&&t.session.modelPolicy?.blockedReason===void 0&&this.publishStarterModelPolicyConfirmed({reason:`policy-save`,machineId:i,session:{...r},policy:eg(t.policy)}))}catch(e){this.canWriteModelPolicyWriteResult(n.id,i,a,o)&&this.setState({modelPolicyError:String(e)})}finally{this.modelPolicySavesInFlight.delete(o);let e=this.isCurrentSessionSelection(n.id,i,a);e&&o>this.modelPolicySettledSaveSeq&&(this.modelPolicySettledSaveSeq=o),!this.disposed&&this.modelPolicySaveSeq===o&&this.setState({isSavingModelPolicy:!1});let t=e?this.getState().status:void 0;t!==void 0&&this.invalidateSupersededModelPolicy(t)}}selectedModelPolicyTarget(){let e=this.getState(),t=e.selectedSession;if(!(t===void 0||t.archived===!0||cg(t)))return{session:{id:t.id,cwd:t.cwd},sessionInfo:{...t},machineId:R(e),selectionSeq:this.selectionSeq}}canWriteModelPolicyReadResult(e,t,n,r,i){return r!==this.modelPolicyLoadSeq||this.modelPolicySavesInFlight.size>0||this.modelPolicySettledSaveSeq!==i?!1:this.isCurrentSessionSelection(e,t,n)}canWriteModelPolicyWriteResult(e,t,n,r){return r===this.modelPolicySaveSeq&&this.isCurrentSessionSelection(e,t,n)}publishStarterModelPolicyConfirmed(e){try{this.onStarterModelPolicyConfirmed?.(e)}catch{}}captureStarterModelPolicySubstitution(e,t,n){if(this.starterModelPolicySubstitutionChecks.has(e.id))return;let r={machineId:t,session:{...e},requestedPolicy:eg(n),observed:!1};this.starterModelPolicySubstitutionChecks.set(e.id,r);let i=this.getState().sessionStatuses[e.id];i!==void 0&&this.runStarterPolicySubstitutionCheck(e.id,i)}plusPendingStartPolicy(e,t){for(let n of this.pendingSessionStarts.values())if(n.cwd===e&&n.machineId===t&&!n.discarded&&n.request.kind===`plus`)return n.request.initialModelPolicy}runStarterPolicySubstitutionCheck(e,t){let n=this.starterModelPolicySubstitutionChecks.get(e);if(n===void 0||n.observed)return;let r=t.modelPolicy;if(r===void 0)return;n.observed=!0;let i=n.requestedPolicy;if(!(i.mode===`exact`?r.mode!==`exact`||!Du(r.resolved,i.exact):r.mode===`exact`))return;let a={machineId:n.machineId,session:{...n.session},requestedPolicy:eg(i),confirmed:{mode:r.mode,resolved:{model:{...r.resolved.model},thinkingLevel:r.resolved.thinkingLevel}}};try{this.onStarterModelPolicySubstitution?.(a)}catch{}}applyConfirmedModelPolicyResponse(e){this.flushPendingUpdates(),this.modelPolicyConfirmedStatus=e.session.modelPolicy,this.setState({modelPolicy:e,modelPolicyError:void 0}),this.applyStatus(e.session)}invalidateSupersededModelPolicy(e){let t=this.getState();t.selectedSession?.id===e.sessionId&&(t.modelPolicy===void 0||e.modelPolicy===void 0||this.modelPolicyConfirmedStatus!==void 0&&(this.modelPolicySavesInFlight.size>0||ng(e.modelPolicy,this.modelPolicyConfirmedStatus)||(this.setState({modelPolicy:void 0}),this.loadModelPolicy())))}clearSelectedModelPolicyState(){return this.modelPolicyLoadSeq=0,this.modelPolicySaveSeq=0,this.modelPolicySettledSaveSeq=0,this.modelPolicySavesInFlight.clear(),this.modelPolicyConfirmedStatus=void 0,{modelPolicy:void 0,isLoadingModelPolicy:!1,isSavingModelPolicy:!1,modelPolicyError:void 0}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.models(e,R(this.getState()))).models}catch(e){return this.setState({error:String(e)}),[]}}async setModel(e,t){let n=this.getState().selectedSession;if(!(!n||n.archived===!0))try{this.applyStatus(await this.api.setModel(n,e,t,R(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async cycleModel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleModel(t,e,R(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.thinkingLevels(e,R(this.getState()))).levels}catch(e){return this.setState({error:String(e)}),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let t=await this.listThinkingLevels();this.getState().selectedSession?.id===e.id&&this.setState({availableThinkingLevels:t})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(t,e,R(this.getState())))}catch(e){this.setState({error:String(e)})}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!(!e||e.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(e,R(this.getState())))}catch(e){this.setState({error:String(e)})}}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||cg(t))return;let n=R(e),r=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,r)&&this.applyStatus(e)}catch(e){this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)})}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||cg(n))return;let r=R(t),i=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,i)&&this.applyStatus(t)}catch(e){this.isCurrentSessionSelection(n.id,r,i)&&this.setState({error:String(e)})}}async stopActiveWork(){let e=this.getState().selectedSession;if(e)try{await this.api.abort(e,R(this.getState()))}catch(e){this.setState({error:String(e)})}}refreshSelectedSession(e=this.getState().selectedSession?.id){let t=this.selectedSessionRefreshTarget(e);return t===void 0?Promise.resolve():this.refreshSelectedSessionTarget(t)}selectedSessionRefreshTarget(e){let t=this.getState().selectedSession;if(!(e===void 0||t?.id!==e||t.archived===!0||cg(t)))return{session:t,machineId:R(this.getState()),selectionSeq:this.selectionSeq}}refreshSelectedSessionTarget(e){return this.requestSelectedSessionRefresh(e).catch(t=>{Uh(t)||this.isCurrentRefreshTarget(e)&&this.setState({error:String(t)})})}requestSelectedSessionRefresh(e){let t=xd(e.machineId,e.session.id);return this.selectedSessionRefreshes.request(t,async()=>{if(!this.isCurrentRefreshTarget(e))return;this.flushPendingUpdates();let n=this.selectionLoad.signal,r=this.extensionStreamGeneration,[i,a,o,s]=await Promise.all([this.api.messages(e.session,{limit:Gh},e.machineId,n),this.api.status(e.session,e.machineId,n),this.api.streamSnapshot(e.session,e.machineId,n).catch(e=>{if(Uh(e))throw e;return{seq:0,partial:null}}),this.api.extensionEntries(e.session,e.machineId,n).catch(e=>{if(Uh(e))throw e;return{entries:[],seq:void 0}}),this.notifications?.refreshSelectedSession(e.session,e.machineId)??Promise.resolve()]);if(!this.isCurrentRefreshTarget(e))return;let c=this.transcripts.mergeHistory(t,i),l=this.transcripts.seedStreamingPartial(c.messages,o.partial);this.streamWatermark={sessionId:e.session.id,seq:o.seq};let u=r===this.extensionStreamGeneration?this.applyExtensionSnapshot(e.session.id,s):{};this.setState({...c,messages:l,status:a,...u,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(a)})}applyExtensionSnapshot(e,t){let n=t.seq;if(n===void 0)return{};let r=this.extensionCursor,i=r?.sessionId===e,a=(this.extensionJournal?.sessionId===e?this.extensionJournal.events:[]).filter(e=>e.seq!==void 0&&e.seq>n).sort((e,t)=>(e.seq??0)-(t.seq??0)),o=t.entries;if(i&&n<r.seq)for(let e of this.getState().sessionExtensionEntries)o=Xh(o,e);for(let e of a)o=Xh(o,e.entry);return this.extensionCursor=i?{sessionId:e,seq:Math.max(n,r.seq)}:{sessionId:e,seq:n},this.extensionJournal={sessionId:e,events:a},{sessionExtensionEntries:o}}applyExtensionEntryEvent(e){let t=this.getState().selectedSession;if(t===void 0)return;let n=this.extensionCursor;if(e.seq!==void 0&&n?.sessionId===t.id&&e.seq<=n.seq||(this.applySessionExtensionEntry(e.entry),e.seq===void 0))return;let r=this.extensionJournal?.sessionId===t.id?this.extensionJournal.events:[];r.push(e),r.length>this.maxJoinBufferedEvents&&r.splice(0,r.length-this.maxJoinBufferedEvents),this.extensionJournal={sessionId:t.id,events:r}}resetExtensionBaseline(){this.extensionCursor=void 0,this.extensionJournal=void 0,this.extensionStreamGeneration+=1}async refreshSelectedExtensionEntries(){let e=this.getState().selectedSession;if(e===void 0||e.archived===!0||cg(e))return;let t=R(this.getState()),n=this.extensionStreamGeneration;try{let r=await this.api.extensionEntries(e,t,this.selectionLoad.signal);if(n!==this.extensionStreamGeneration||!this.isSelectedSessionIdentity(e.id,t))return;this.setState(this.applyExtensionSnapshot(e.id,r))}catch(e){if(Uh(e))return}}isCurrentRefreshTarget(e){return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)}isCurrentSessionSelection(e,t,n){return this.isCurrentHistoryTarget(e,t,n)&&this.isSelectedSessionIdentity(e,t)}isCurrentHistoryTarget(e,t,n){if(this.disposed||n!==this.selectionSeq)return!1;let r=this.getState();return R(r)===t&&r.selectedSession?.id===e}isCurrentSessionOrderScope(e,t,n){let r=this.getState();return!this.disposed&&n===this.selectionSeq&&R(r)===e&&r.selectedWorkspace?.id===t}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return R(n)===t&&r?.id===e&&r.archived!==!0&&!cg(r)}applyBulkSessionFailures(e,t){t.length!==0&&this.setState({error:`${e} failed for ${String(t.length)} session${t.length===1?``:`s`}: ${t.join(`; `)}`})}sessionCacheKey(e){return xd(R(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}sessionPersistenceOptions(){let e=this.getState();return xh(e.machineRuntimes[R(e)])}workspaceSelectionKey(e){return`${R(this.getState())}:${e}`}replaceSession(e){let t=this.getState(),n=t.selectedSession;this.setState({sessions:t.sessions.map(t=>t.id===e.id?e:t),projectSessions:t.projectSessions.map(t=>t.id===e.id?e:t),selectedSession:n?.id===e.id?e:n})}createPendingSessionStart(e,t,n){let r=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,i=new Date().toISOString(),a=n.kind===`plus`?{kind:`plus`,initialModelPolicy:eg(n.initialModelPolicy)}:n,o={id:r,path:`pi-webui://pending-session/${r}`,cwd:e.path,persisted:!1,name:`New session`,created:i,modified:i,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t,...a.kind===`plus`?{creationSource:`session-list-plus`}:{}};return{tempId:r,workspaceId:e.id,cwd:e.path,machineId:t,session:o,queuedSends:[],discarded:!1,request:a}}insertAndSelectPendingSession(e){let t=this.getState();this.selectClientPendingStartSession(e,{activity:lg(e.id),sessions:[e,...t.sessions.filter(t=>t.id!==e.id)]})}selectClientPendingStartSession(e,t){this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.selectionLoad.abort(),this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:lg(e.id,r.queuedSends.length));this.setState({...t?.sessions===void 0?{}:{sessions:t.sessions},selectedSession:e,messages:[],sessionExtensionEntries:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,availableThinkingLevels:[],...this.clearSelectedModelPolicyState(),treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return!1;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){for(let e of r)e.onDelivered?.(!1);return Lp(xd(n.machineId,e)),this.attachmentDrafts.clear(xd(n.machineId,e)),this.setState({clientQueuedSessionMessages:rg(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{}),!1}n.request.kind===`plus`&&this.captureStarterModelPolicySubstitution(t,n.machineId,n.request.initialModelPolicy),Bf(t,n.machineId),Rp(xd(n.machineId,e),xd(n.machineId,t.id)),this.attachmentDrafts.move(xd(n.machineId,e),xd(n.machineId,t.id));let a=Vf(t,n.machineId);if(!this.isCurrentPendingStart(n))return this.setState({clientQueuedSessionMessages:rg(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r),!1;let o=this.getState(),s=o.selectedSession?.id===e;return this.setState({sessions:sg(o.sessions,e,a),sessionActivities:$h(o.sessionActivities,e),sendingPrompts:ag(o.sendingPrompts,e,a.id),clientQueuedSessionMessages:ag(o.clientQueuedSessionMessages,e,a.id),...s?{selectedSession:a,status:o.sessionStatuses[a.id],activity:o.sessionActivities[a.id]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),s&&(this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1})),await this.flushQueuedPendingSends(a,n.machineId,r),!0}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);for(let e of n.queuedSends)e.onDelivered?.(!1);let r=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),i=this.isCurrentPendingStart(n);if(n.discarded||!i){i&&this.applyReleasedCreatedSessions(r,n.machineId);return}let a=this.getState(),o=xg(t),s=ug(e,o,n.queuedSends.length),c=a.sessions.some(t=>t.id===e);this.setState({sessions:c?a.sessions:[n.session,...a.sessions],sessionActivities:{...a.sessionActivities,[e]:s},activity:a.selectedSession?.id===e?s:a.activity,error:`Failed to start session: ${o}`}),this.applyReleasedCreatedSessions(r,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return R(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd!==e||i.machineId!==t||(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||R(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>cg(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t){try{let n=R(this.getState()),r=await this.api.startSession(e.cwd,n);Bf(r,n),Rp(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),this.attachmentDrafts.move(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),Hf(e.id,n);let i=Vf(r,n);this.setState({sessions:[i,...this.getState().sessions.filter(t=>t.id!==e.id)],error:``}),await this.selectSession(i,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(e){this.setState({error:String(e)})}}markCachedNewSessionPersisted(e){if(!Wf(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Gf(t))}applyCommandResult(e){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let t=(e.type,e.message);if(t!==void 0&&t!==``&&this.setState({messages:[...this.getState().messages,tp(e.type===`unsupported`?`system`:`tool`,t)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&Ip(this.sessionCacheKey(e.session.id),e.promptDraft);let t=this.getState().selectedSession,n=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];this.setState({sessions:n,selectedSession:t?.id===e.session.id?e.session:t}),t?.id!==e.session.id&&this.selectSession(e.session)}}applyCreatedSession(e){let t=this.getState(),n=t.selectedWorkspace?.path===e.cwd||t.workspaces.some(t=>t.path===e.cwd)?og(t.projectSessions,e):t.projectSessions;if(t.selectedWorkspace?.path!==e.cwd){n!==t.projectSessions&&this.setState({projectSessions:n});return}if(t.sessions.some(t=>t.id===e.id)){n!==t.projectSessions&&this.setState({projectSessions:n});return}let r=R(t);if(this.hasPendingStartFor(e.cwd,r)){let i=this.plusPendingStartPolicy(e.cwd,r);i!==void 0&&this.captureStarterModelPolicySubstitution(e,r,i),this.suppressedCreatedSessions.set(e.id,{session:e,machineId:r}),n!==t.projectSessions&&this.setState({projectSessions:n});return}this.setState({sessions:[e,...t.sessions],projectSessions:n})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.sessionActivities[e.sessionId]?.phase===`active`&&!vd(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Eg(t,e.sessionId,e.messageCount),...n?{sessionActivities:$h(t.sessionActivities,e.sessionId)}:{},status:t.selectedSession?.id===e.sessionId?e:t.status,activity:t.selectedSession?.id===e.sessionId&&n?void 0:t.activity}),this.invalidateSupersededModelPolicy(e),this.runStarterPolicySubstitutionCheck(e.sessionId,e)}applySessionExtensionEntry(e){this.setState({sessionExtensionEntries:Xh(this.getState().sessionExtensionEntries,e)})}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession,i=this.getState();this.setState({sessions:i.sessions.map(n),projectSessions:i.projectSessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(R(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(R(this.getState()),e.notificationId)===!0)return;if(e.type===`session.extensionEntry`){this.applyExtensionEntryEvent(e);return}if(e.type===`session.subscribed`){this.refreshSelectedExtensionEntries();return}if(this.isStreamEventBelowWatermark(e))return;if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(lh(e)){this.queueTranscriptEvent(e);return}this.flushPendingUpdates();let t=this.transcripts.applyLiveEvent(this.getState().messages,e);t?this.setState({messages:t}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name),e.type===`agent.end`&&this.refreshSelectedSession()}applyJoinBufferedEvents(e,t){if(e.overflowed){this.requestOverloadResync(t);return}for(let t of e.drain())this.applyEvent(t)}queueTranscriptEvent(e){this.streamEventBuffer.enqueue(e),this.schedulePendingFlush()}pendingTranscriptEventCount(){return this.streamEventBuffer.eventCount}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){let{events:e,resyncRequired:t}=this.streamEventBuffer.drain();if(e.length>0){let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(t&&this.requestOverloadResync(),this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}requestOverloadResync(e=this.selectedSessionRefreshTarget(this.getState().selectedSession?.id)){if(e===void 0||!this.isCurrentRefreshTarget(e))return;let t=this.now(),n=this.lastOverloadResyncAt;if(n!==void 0){let r=t-n;if(r<Kh){this.scheduleDeferredOverloadResync(e,Kh-r);return}}this.cancelPendingOverloadResync(),this.lastOverloadResyncAt=t,this.refreshSelectedSessionTarget(e)}scheduleDeferredOverloadResync(e,t){if(this.pendingOverloadResync!==void 0)return;let n={cancel:()=>void 0};this.pendingOverloadResync=n,n.cancel=this.scheduleOverloadResync(()=>{this.pendingOverloadResync===n&&(this.pendingOverloadResync=void 0,this.requestOverloadResync(e))},t)}cancelPendingOverloadResync(){let e=this.pendingOverloadResync;e!==void 0&&(this.pendingOverloadResync=void 0,e.cancel())}clearPendingUpdates(){this.cancelPendingOverloadResync(),this.streamEventBuffer.clear(),this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}isStreamEventBelowWatermark(e){let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}};function $h(e,t){return rg(e,t)}function eg(e){return{mode:e.mode,exact:{model:{provider:e.exact.model.provider,id:e.exact.model.id},thinkingLevel:e.exact.thinkingLevel},...e.tier===void 0?{}:{tier:e.tier}}}function tg(e){return e.creationSource===`session-list-plus`&&e.parentSessionPath===void 0&&e.archived!==!0}function ng(e,t){return e.mode===t.mode&&e.tier===t.tier&&e.blockedReason===t.blockedReason&&e.resolved.thinkingLevel===t.resolved.thinkingLevel&&e.resolved.model.provider===t.resolved.model.provider&&e.resolved.model.id===t.resolved.model.id}function rg(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function ig(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function ag(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...rg(e,t),[n]:r}}function og(e,t){return e.find(e=>e.id===t.id||e.path===t.path)===t?e:[t,...e.filter(e=>e.id!==t.id&&e.path!==t.path)]}function sg(e,t,n){let r=[],i=!1;for(let a of e){if(a.id===t){i||=(r.push(n),!0);continue}a.id!==n.id&&r.push(a)}return i?r:[n,...r]}function cg(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function lg(e,t=0){return{sessionId:e,phase:`active`,label:`Creating session`,detail:t>0?`${String(t)} queued ${t===1?`message`:`messages`} will send when the backend session is ready`:`Waiting for the backend session to be ready`,at:new Date().toISOString()}}function ug(e,t,n=0){return{sessionId:e,phase:`error`,label:`Session creation failed`,detail:`${t}${n>0?` · ${String(n)} queued ${n===1?`message`:`messages`} kept below`:``}`,at:new Date().toISOString()}}function dg(e){return e.type===`prompt`?{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:fg(e.text,e.attachments)}:{kind:`followUp`,text:e.text}}function fg(e,t){let n=pg(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function pg(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=`${String(n)} ${n===1?`attachment`:`attachments`}`;return t.length===0?`[${r} queued]`:`[${r} queued: ${t.slice(0,3).join(`, `)}${t.length>3?`, +${String(t.length-3)} more`:``}]`}function mg(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function hg(e){return e.filter(yg).map(e=>e.value)}function gg(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function _g(e,t){return t.flatMap((t,n)=>bg(t)?[`${e[n]?.id??`unknown`}: ${xg(t.reason)}`]:[])}async function vg(e,t,n){let r=e.map((e,t)=>({item:e,index:t})),i=[],a=0;async function o(){for(;a<r.length;){let e=r[a];if(e===void 0)return;a+=1;try{i[e.index]={status:`fulfilled`,value:await n(e.item)}}catch(t){i[e.index]={status:`rejected`,reason:t}}}}let s=Math.min(Math.max(1,t),r.length);return await Promise.all(Array.from({length:s},()=>o())),i}function yg(e){return e.status===`fulfilled`}function bg(e){return e.status===`rejected`}function xg(e){return e instanceof Error?e.message:String(e)}function Sg(e,t){let n=new Map(t.map(e=>[Tg(e),e]));return e.map(e=>{let t=n.get(Tg(e));return t===void 0||e.manualOrder===t.manualOrder?e:{...e,manualOrder:t.manualOrder}})}function Cg(e,t){let n=new Set(t.map(Tg));return e.flatMap(e=>n.has(Tg(e))?[{id:e.id,cwd:e.cwd,manualOrder:e.manualOrder}]:[])}function wg(e,t){let n=new Map(t.map(e=>[Tg(e),e]));return e.map(e=>{let t=n.get(Tg(e));if(t===void 0)return e;if(t.manualOrder===void 0){if(!Object.hasOwn(e,`manualOrder`))return e;let{manualOrder:t,...n}=e;return n}return e.manualOrder===t.manualOrder?e:{...e,manualOrder:t.manualOrder}})}function Tg(e){return JSON.stringify([e.cwd,e.id])}function Eg(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.projectSessions.some(e=>e.id===t&&e.messageCount!==n)?e.projectSessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,a=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===void 0?{}:{projectSessions:i},...a===e.selectedSession?{}:{selectedSession:a}}}function Dg(e){return e instanceof Error&&e.message.toLowerCase().includes(`session not found`)}var Og={order:0,overflowWatermark:0};function kg(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Og,optimisticDismissedIds:[],announcements:[]}}function Ag(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&Wg(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function jg(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??kg(t),needsRefresh:!1,changed:!1};if(e===void 0||!Wg(e,t))return{value:Kg(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:Kg(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[];break}let o=i[0]?.order??0;if(!qg(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function Mg(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=Yg(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...Xg(Jg(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function Ng(e){return e===`error`?`Error`:e===`warning`?`Warning`:`Info`}function Pg(e){return`${Ng(e.severity)} notification received.`}function Fg(e){return e.retainedCount+e.discardedCount}function Ig(e){return`Notifications (${String(Fg(e))})`}function Lg(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return`Dismiss ${Ng(e.severity).toLowerCase()} notification`;let n=Array.from(t);return`Dismiss notification: ${n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`}`}function Rg(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function zg(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Bg(e,t){return e.has(zg(t))}function Vg(e,t,n){let r=new Set(e),i=zg(t);return n?r.add(i):r.delete(i),r}function Hg(e){return`${String(e)} older ${e===1?`notification`:`notifications`} not shown.`}function Ug(e){if(!e.truncated)return;let t=Kt/1024;return`Message truncated at ${String(t)} KiB.`}function Wg(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function Gg(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function Kg(e){return{...kg(e),status:`stale`}}function qg(e,t){return e.length===t.retainedCount&&Jg(e)===t.highestSeverity}function Jg(e){let t;for(let n of e)t=Gg(t,n.severity);return t}function Yg(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function Xg(e){return e===void 0?{}:{highestSeverity:e}}var Zg=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.acceptedSupportByMachine=new Set,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??Lc,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.acceptedSupportByMachine.clear(),this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){if(this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0||!this.machineSupportsNotifications(t)){this.setState({selectedNotificationInbox:void 0});return}this.setState({selectedNotificationInbox:kg(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineSupportsNotifications(t)||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;this.acceptedSupportByMachine.add(e);let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=jg(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;e.machines!==t.machines&&this.pruneRemovedMachines(t.machines);let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||e.machineRuntimes!==t.machineRuntimes,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineSupportsNotificationsInState(e,r.machineId)&&this.machineIsReachableInState(e,r.machineId);if(!this.machineSupportsNotifications(r.machineId)||!this.machineIsReachable(r.machineId)){this.markSelectedStale(r);return}this.ensureSelectedProjection(r),(!i||this.getState().selectedNotificationInbox?.status!==`fresh`)&&this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId)}shouldFilterLegacyNotification(e,t){return t!==void 0&&t!==``&&this.machineSupportsNotifications(e)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=Mg(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=Qg(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:`Failed to dismiss notification: ${e_(t)}`}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Mg(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=Qg(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:`Failed to dismiss session notifications: ${e_(e)}`}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineSupportsNotifications(t.machineId)||!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}this.acceptedSupportByMachine.add(t.machineId);let i=this.getState().selectedNotificationInbox,a=i===void 0||$g(i,t,r)?Ag(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=jg(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&Wg(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!Wg(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=$g(r,e,t)?Ag(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n===void 0||!Wg(n,e)||this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;(t===void 0||!Wg(t,e))&&this.setState({selectedNotificationInbox:kg(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Wg(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t===void 0||!Wg(t,e)||t.status===`stale`||this.setState({selectedNotificationInbox:{...t,status:`stale`}})}pruneRemovedMachines(e){let t=new Set(e.map(e=>e.id));t.size===0&&t.add(`local`);for(let e of[...this.acceptedSupportByMachine])t.has(e)||this.acceptedSupportByMachine.delete(e)}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Wg(this.selectedTarget,e)}machineSupportsNotifications(e){return this.machineSupportsNotificationsInState(this.getState(),e)}machineSupportsNotificationsInState(e,t){return this.acceptedSupportByMachine.has(t)||e.machineRuntimes[t]?.ok===!0&&E(e.machineRuntimes[t],w.sessionsNotifications)}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function Qg(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function $g(e,t,n){return!Wg(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function e_(e){return e instanceof Error?e.message:String(e)}var t_={available:!1,reason:`Checking OS speech availability.`,voices:[]},n_=5e3,r_=class{constructor(e={}){this.statusValue=a_(t_),this.loadingStatusValue=!1,this.config=Mn(void 0),this.errorClearSequence=0,this.statusRequestSequence=0,this.disposed=!1,this.api=e.api??Zs,this.createRunId=e.createRunId??u_,this.onStateChange=e.onStateChange??(()=>void 0),this.scheduleErrorClear=e.scheduleErrorClear??l_}get snapshot(){return{status:a_(this.statusValue),loadingStatus:this.loadingStatusValue,...this.active===void 0?{}:{active:{runId:this.active.runId,sessionId:this.active.sessionId,messageKey:this.active.messageKey}},...this.errorValue===void 0?{}:{error:this.errorValue}}}configure(e){this.disposed||(this.config=Mn(e))}async refreshStatus(){if(this.disposed)return;let e=++this.statusRequestSequence;this.loadingStatusValue=!0,this.publish();try{let t=await this.api.status();if(!this.isCurrentStatusRequest(e))return;this.statusValue=a_(t)}catch(t){if(!this.isCurrentStatusRequest(e))return;this.statusValue=i_(c_(t))}finally{this.isCurrentStatusRequest(e)&&(this.loadingStatusValue=!1,this.publish())}}select(e){if(this.disposed||o_(this.selection,e))return;this.selection=e===void 0?void 0:{...e};let t=this.clearActive();t!==void 0&&(t.controller.abort(),this.publish(),this.stopAbandoned(t))}async startManual(e){if(this.disposed||!this.canStart(e))return;let t=Nn(e.text);if(t===``)return;let n=this.clearActive();n!==void 0&&(n.controller.abort(),this.stopAbandoned(n));let r=this.createRunId(),i={runId:r,machineId:e.machineId,sessionId:e.sessionId,messageKey:e.messageKey,text:t,controller:new AbortController,requestClosed:!1};this.active=i,this.clearRetryableError(),this.publish();let a=this.config.voice,o={runId:r,text:t,...a!==void 0&&this.statusValue.voices.some(e=>e.name===a)?{voice:a}:{},rate:this.config.rate};try{let e=await this.api.speak(o,i.controller.signal);if(i.requestClosed=!0,!this.isActive(i)||e.runId!==i.runId)return;this.active=void 0,this.publish()}catch(e){if(i.requestClosed=!0,!this.isActive(i))return;if(s_(e)){this.active=void 0,this.publish();return}if(this.active=void 0,e instanceof Qt&&e.status===503){this.statusValue=i_(e.message),this.clearRetryableError(),this.publish();return}this.applyRetryableError(c_(e)),this.publish(),e instanceof Qt&&e.status===500&&this.refreshStatus()}}matchesActiveSource(e){let t=this.active;return t?.sessionId===e.sessionId&&t.messageKey===e.messageKey&&t.text===e.text}async stop(){if(this.disposed)return;let e=this.clearActive();e!==void 0&&(e.controller.abort(),this.publish(),await this.stopActive(e))}dispose(){if(this.disposed)return;this.disposed=!0,this.statusRequestSequence+=1,this.clearError?.(),this.clearError=void 0;let e=this.clearActive();e!==void 0&&(e.controller.abort(),Promise.resolve().then(()=>this.api.stop(e.runId)).catch(()=>void 0))}canStart(e){let t=this.selection;return t?.machineId===`local`&&t.machineId===e.machineId&&t.sessionId===e.sessionId&&this.statusValue.available}clearActive(){let e=this.active;return this.active=void 0,e}isActive(e){return!this.disposed&&this.active===e}isCurrentStatusRequest(e){return!this.disposed&&e===this.statusRequestSequence}async stopAbandoned(e){try{await this.api.stop(e.runId)}catch{}}async stopActive(e){try{await this.api.stop(e.runId)}catch(t){if(await Promise.resolve(),this.disposed||e.requestClosed)return;this.applyRetryableError(c_(t)),this.publish()}}applyRetryableError(e){this.clearError?.(),this.errorValue=e;let t=++this.errorClearSequence;this.clearError=this.scheduleErrorClear(()=>{this.disposed||t!==this.errorClearSequence||(this.errorValue=void 0,this.clearError=void 0,this.publish())},n_)}clearRetryableError(){this.clearError?.(),this.errorClearSequence+=1,this.clearError=void 0,this.errorValue=void 0}publish(){this.disposed||this.onStateChange()}};function i_(e){return{available:!1,reason:e.trim()===``?`Host speech is unavailable.`:e,voices:[]}}function a_(e){return{available:e.available,...e.reason===void 0?{}:{reason:e.reason},voices:e.voices.map(e=>({...e}))}}function o_(e,t){return e?.machineId===t?.machineId&&e?.sessionId===t?.sessionId}function s_(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`}function c_(e){return e instanceof Error?e.message:String(e)}function l_(e,t){let n=globalThis.setTimeout(e,t);return()=>{globalThis.clearTimeout(n)}}function u_(){let e=globalThis.crypto;if(typeof e.randomUUID==`function`)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));return`r${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function d_(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var f_=d_();function p_(e){f_=e}var m_={exec:()=>null};function h_(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function B(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(__.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var g_=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),__={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:h_(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:h_(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:h_(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:h_(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:h_(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:h_(e=>RegExp(`^ {0,${e}}>`))},v_=/^(?:[ \t]*(?:\n|$))+/,y_=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,b_=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,x_=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,S_=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,C_=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,w_=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,T_=B(w_).replace(/bull/g,C_).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),E_=B(w_).replace(/bull/g,C_).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),D_=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,O_=/^[^\n]+/,k_=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,A_=B(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,k_).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),j_=B(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,C_).getRegex(),M_=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,N_=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,P_=B(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,N_).replace(`tag`,M_).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),F_=e=>B(D_).replace(`hr`,x_).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,M_).getRegex(),I_=F_(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),L_=F_(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),R_={blockquote:B(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,L_).getRegex(),code:y_,def:A_,fences:b_,heading:S_,hr:x_,html:P_,lheading:T_,list:j_,newline:v_,paragraph:I_,table:m_,text:O_},z_=B(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,x_).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,M_).getRegex(),B_={...R_,lheading:E_,table:z_,paragraph:B(D_).replace(`hr`,x_).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,z_).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,M_).getRegex()},V_={...R_,html:B(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,N_).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:m_,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:B(D_).replace(`hr`,x_).replace(`heading`,` *#{1,6} *[^
22
+ `))+1;return e.slice(t)}var Xm=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),sh(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=Rc(e,this.machineId);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){let r=Qm(await oh(e));this.socket!==t||r===void 0||r.type===`notifications.inbox`&&(n.id!==r.summary.sessionId||n.cwd!==r.summary.cwd)||this.onEvent?.(r)}},Zm=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),sh(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=Bc(this.machineId);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){let n=$m(await oh(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function Qm(e){return ah(e)===`notifications.inbox`?rh(()=>Kr(e)):eh(e)?e:void 0}function $m(e){if(ah(e)===`sessions.unread`)return ih(()=>zr(e));if(th(e)||nh(e))return e}function eh(e){return[`message.append`,`assistant.delta`,`assistant.thinking.delta`,`tool.start`,`tool.update`,`tool.end`,`shell.start`,`shell.chunk`,`shell.end`,`agent.start`,`agent.end`,`message.end`,`status.update`,`activity.update`,`command.output`,`session.extensionEntry`,`session.subscribed`,`session.error`,`session.name`,`session.created`,`pi.event`].includes(ah(e))}function th(e){let t=ah(e);return t===`status.update`||t===`activity.update`||t===`session.name`||t===`session.created`}function nh(e){let t=ah(e);return t===`terminal.created`||t===`terminal.exited`||t===`terminal.closed`||t===`workspace.activity`}function rh(e){return ih(e)}function ih(e){try{return e()}catch{return}}function ah(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function oh(e){try{return typeof e==`string`?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function sh(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}var ch=new TextEncoder;function lh(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`||e.type===`tool.update`}var uh=class{constructor(e={}){this.runs=[],this.toolUpdateRuns=new Map,this.pendingByteCount=0,this.resyncRequired=!1,this.maxEventRuns=e.maxEventRuns??128,this.maxBytes=e.maxBytes??262144,this.maxToolUpdateKeys=e.maxToolUpdateKeys??64}get eventCount(){return this.runs.length+this.toolUpdateRuns.size}get pendingBytes(){return this.pendingByteCount}enqueue(e){if(!(this.resyncRequired||!lh(e))){if(e.type===`tool.update`){this.enqueueToolUpdate(e);return}this.enqueueAccumulating(e)}}enqueueToolUpdate(e){let t=this.toolUpdateRuns.get(e.toolCallId);if(t!==void 0){t.latest=gh(e),t.seq=vh(t.seq,e.seq);return}if(this.toolUpdateRuns.size+1>this.maxToolUpdateKeys){this.markResyncRequired();return}this.toolUpdateRuns.set(e.toolCallId,{type:`tool.update`,toolCallId:e.toolCallId,latest:gh(e),seq:e.seq})}enqueueAccumulating(e){let t=this.runs.at(-1),n=t!==void 0&&dh(t,e),r=this.runs.length+ +!n,i=n?ph(t,e):yh(e),a=n?t.bytes:0,o=this.pendingByteCount-a+i;if(r>this.maxEventRuns||o>this.maxBytes){this.markResyncRequired();return}if(n){mh(t,e,i),this.pendingByteCount=o;return}this.runs.push(fh(e,i)),this.pendingByteCount=o}drain(){if(this.resyncRequired)return this.resyncRequired=!1,{events:[],resyncRequired:!0};let e=[];for(let t of this.runs)e.push(hh(t));for(let t of this.toolUpdateRuns.values())e.push(_h(t.latest,t.seq));return this.reset(),{events:e,resyncRequired:!1}}clear(){this.reset(),this.resyncRequired=!1}reset(){this.runs=[],this.toolUpdateRuns.clear(),this.pendingByteCount=0}markResyncRequired(){this.reset(),this.resyncRequired=!0}};function dh(e,t){switch(e.type){case`assistant.delta`:return t.type===`assistant.delta`;case`assistant.thinking.delta`:return t.type===`assistant.thinking.delta`;case`shell.chunk`:return t.type===`shell.chunk`}}function fh(e,t){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`?{type:e.type,chunks:[e.text],seq:e.seq,bytes:t}:{type:e.type,chunks:[e.chunk],seq:e.seq,bytes:t}}function ph(e,t){return e.bytes+yh(t)}function mh(e,t,n){if(e.type===`assistant.delta`&&t.type===`assistant.delta`){e.chunks.push(t.text),e.seq=vh(e.seq,t.seq),e.bytes=n;return}if(e.type===`assistant.thinking.delta`&&t.type===`assistant.thinking.delta`){e.chunks.push(t.text),e.seq=vh(e.seq,t.seq),e.bytes=n;return}e.type===`shell.chunk`&&t.type===`shell.chunk`&&(e.chunks.push(t.chunk),e.seq=vh(e.seq,t.seq),e.bytes=n)}function hh(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`?_h({type:e.type,text:e.chunks.join(``)},e.seq):_h({type:e.type,chunk:e.chunks.join(``)},e.seq)}function gh(e){return{type:e.type,toolName:e.toolName,toolCallId:e.toolCallId,text:e.text,...e.content===void 0?{}:{content:e.content},...e.details===void 0?{}:{details:e.details}}}function _h(e,t){return t===void 0?e:{...e,seq:t}}function vh(e,t){return e===void 0?t:t===void 0?e:Math.max(e,t)}function yh(e){return ch.encode(JSON.stringify(e)).byteLength}function bh(e){return e?.ok===!0&&E(e,w.sessionsPersistedState)}function xh(e){return{authoritative:bh(e)}}function Sh(e,t,n={}){if(e===void 0)return`unknown`;let r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?`persisted`:r===!1||Wf(e)?`transient`:n.authoritative===!0?`unknown`:`persisted`}function Ch(e,t,n){return e!==void 0&&e.archived!==!0&&Sh(e,t,n)===`persisted`}function wh(e,t,n){return e!==void 0&&e.archived!==!0&&Sh(e,t,n)===`transient`}function Th(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Eh=class{constructor(e,t,n=Th()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Oh(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 Dh(e){return typeof e==`string`&&e!==``?e:void 0}function Oh(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!kh(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 kh(e){return!Ah(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 Ah(e){return typeof e==`object`&&!!e}var jh=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},Mh=`pi-webui:session-selection:v1`,Nh=class{constructor(e=Th()){this.sessionIdsByCwd=new Eh(Mh,Dh,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function Ph(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return Ih(e,n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function Fh(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function Ih(e,t){return e.find(e=>e.id===t||e.id.startsWith(t))}function Lh(e,t,n){return Rh(e,[t],n)}function Rh(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function zh(e,t,n){return Bh(e,t,[n])}function Bh(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}var Vh=class{get signal(){return this.controller?.signal}restart(){this.abort();let e=new AbortController;return this.controller=e,e.signal}abort(){let e=this.controller;e!==void 0&&(this.controller=void 0,e.abort(new Hh))}},Hh=class extends Error{constructor(){super(`Load cancelled because the selection changed`),this.name=`LoadCancelledError`}};function Uh(e){return e instanceof Hh||Wh(e)&&e.name===`AbortError`}function Wh(e){return typeof e==`object`&&!!e&&`name`in e}var Gh=100,Kh=1e3,qh=4,Jh=512,Yh=(e,t)=>{let n=globalThis.setTimeout(e,t);return()=>{globalThis.clearTimeout(n)}};function Xh(e,t){let n=t.entryId===``?-1:e.findIndex(e=>e.entryId===t.entryId),r=n===-1?[...e,t]:e.map((e,r)=>r===n?t:e);return r.length>200?r.slice(r.length-200):r}var Zh=class{constructor(e){this.maxEvents=e,this.events=[],this.overflow=!1}get overflowed(){return this.overflow}push(e){if(!this.overflow){if(this.events.length>=this.maxEvents){this.events=[],this.overflow=!0;return}this.events.push(e)}}drain(){let e=this.events;return this.events=[],e}},Qh=class{constructor(e,t,n,r=new jh,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectionSeq=0,this.extensionStreamGeneration=0,this.sessionReorderInFlight=!1,this.disposed=!1,this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.modelPolicyIssueSeq=0,this.modelPolicyLoadSeq=0,this.modelPolicySaveSeq=0,this.modelPolicySettledSaveSeq=0,this.modelPolicySavesInFlight=new Set,this.pendingSessionStarts=new Map,this.starterModelPolicySubstitutionChecks=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new Sd,this.selectionLoad=new Vh,this.socket=i.socket??new Xm,this.api=i.api??Lc,this.attachmentDrafts=i.attachmentDrafts??jp,this.transcripts=i.transcripts??new Rm,this.streamEventBuffer=i.streamEventBuffer??new uh,this.now=i.now??(()=>Date.now()),this.scheduleOverloadResync=i.scheduleOverloadResync??Yh,this.maxJoinBufferedEvents=i.maxJoinBufferedEvents??Jh,this.notifications=i.notifications,this.replacePromptEditorText=i.replacePromptEditorText,this.onSelectedSessionReady=i.onSelectedSessionReady,this.onStarterModelPolicyConfirmed=i.onStarterModelPolicyConfirmed,this.onStarterModelPolicySubstitution=i.onStarterModelPolicySubstitution,this.refreshProjectSessionCatalog=i.refreshProjectSessionCatalog??(()=>void 0)}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}dispose(){this.disposed=!0,this.selectionSeq+=1,this.selectionLoad.abort(),this.socket.close(),this.clearPendingUpdates(),this.starterModelPolicySubstitutionChecks.clear()}clearActiveSession(){this.selectionSeq+=1,this.selectionLoad.abort(),this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.resetExtensionBaseline(),this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],sessionExtensionEntries:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,availableThinkingLevels:[],...this.clearSelectedModelPolicyState(),treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){let e=this.getState();Fh(e.sessions,e.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(e){return this.startSessionRequest({kind:`legacy`,...e===void 0?{}:{modelPolicy:e}})}async startPlusSession(e){return this.startSessionRequest({kind:`plus`,initialModelPolicy:e})}async startSessionRequest(e){let t=this.getState().selectedWorkspace;if(!t)return!1;let n=R(this.getState()),r=this.createPendingSessionStart(t,n,e);this.pendingSessionStarts.set(r.tempId,r);try{this.insertAndSelectPendingSession(r.session)}catch(e){throw this.failPendingSessionStart(r.tempId,e),e}try{let e=r.request.kind===`plus`?await this.api.startPlusSession(t.path,r.request.initialModelPolicy,n):await this.api.startSession(t.path,n,r.request.modelPolicy);return await this.resolvePendingSessionStart(r.tempId,e),!r.discarded&&r.request.kind===`plus`&&e.creationSource===`session-list-plus`&&this.publishStarterModelPolicyConfirmed({reason:`creation`,machineId:n,session:{...e},requestedPolicy:r.request.initialModelPolicy}),!0}catch(e){return this.failPendingSessionStart(r.tempId,e),!1}}async startSessionWithPrompt(e,t,n,r=`inline`,i,a){return this.startSessionWithPromptRequest(e,t,n,r,{kind:`legacy`,...i===void 0?{}:{modelPolicy:i}},a)}async startPlusSessionWithPrompt(e,t,n,r,i,a){return this.startSessionWithPromptRequest(e,t,n,r,{kind:`plus`,initialModelPolicy:i},a)}async startSessionWithPromptRequest(e,t,n,r,i,a){let o=this.startSessionRequest(i).then(e=>({rejected:!1,started:e}),e=>({rejected:!0,started:!1,error:e})),s;try{s=await this.send(e,t,n,r,!0)}finally{a?.((await o).started)}let c=await o;if(c.rejected)throw c.error;return c.started&&s}preferredSession(e,t,n){return Ph(t,{targetSessionId:n,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e))})}async selectSession(e,t){if(this.disposed)return;if(cg(e)){this.selectClientPendingStartSession(e,t);return}this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let n=++this.selectionSeq;this.selectionLoad.restart(),this.socket.close(),this.streamWatermark=void 0,this.resetExtensionBaseline(),this.clearPendingUpdates();let r=R(this.getState());this.notifications?.prepareSelectedSession(e,r);let i=this.sessionCacheKey(e.id),a=this.transcripts.cachedView(i);this.setState({selectedSession:e,...a,sessionExtensionEntries:[],isLoadingEarlierMessages:!1,...t?.preserveTreeDialog===!0?{}:{treeDialog:void 0},status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],availableThinkingLevels:[],...this.clearSelectedModelPolicyState()});let o;try{if(e.archived===!0){let a=await this.api.messages(e,{limit:Gh},R(this.getState()),this.selectionLoad.signal);if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let o=this.transcripts.mergeHistory(i,a);this.setState({...o,isLoadingEarlierMessages:!1,status:void 0,activity:void 0}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl();return}let a={session:e,machineId:r,selectionSeq:n},s=new Zh(this.maxJoinBufferedEvents);if(o=s,this.socket.connect(e,e=>{s.push(e)},()=>{s=new Zh(this.maxJoinBufferedEvents),o=s,this.resetExtensionBaseline(),this.refreshSelectedSession(e.id)},r,()=>{this.notifications?.refreshSelectedSession(e,r)}),await this.requestSelectedSessionRefresh(a),!this.isCurrentRefreshTarget(a))return;this.refreshAvailableThinkingLevels(),this.applyJoinBufferedEvents(s,a),this.socket.setHandler(e=>{this.applyEvent(e)}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(i){if(Uh(i))return;if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(t?.propagateRefreshError===!0&&this.isSelectedSessionIdentity(e.id,r))throw i;return}if(Wf(e)&&Dg(i)){await this.recreateCachedNewSession(e,t);return}if(o!==void 0){if(!o.overflowed)for(let e of o.drain())this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)})}if(this.setState({error:String(i)}),t?.propagateRefreshError===!0)throw i}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)return;let n=R(e),r=this.selectionSeq,i=this.selectionLoad.signal;this.setState({isLoadingEarlierMessages:!0});try{let a=await this.api.messages(t,{before:e.messagePageStart,limit:Gh},n,i);if(!this.isCurrentHistoryTarget(t.id,n,r))return;let o=this.transcripts.mergeHistory(this.sessionCacheKey(t.id),a);this.setState(o)}catch(e){!Uh(e)&&this.isCurrentHistoryTarget(t.id,n,r)&&this.setState({error:String(e)})}finally{this.isCurrentHistoryTarget(t.id,n,r)&&this.setState({isLoadingEarlierMessages:!1})}}async send(e,t,n,r=`inline`,i=!1){return await this.sendWithPendingOutcome(e,t,n,r,i)}async sendWithPendingOutcome(e,t,n,r,i){let a=this.getState().selectedSession;if(!a||a.archived===!0)return!1;let o=e.trim(),s=n!==void 0&&n.length>0;if(cg(a)){let c=!s&&o.startsWith(`/`)?{type:`command`,text:e}:!s&&qm(e)?{type:`shell`,text:e}:{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r};return i?await new Promise(e=>{this.enqueuePendingSessionSend(a,c,e)||e(!1)}):this.enqueuePendingSessionSend(a,c)}return!s&&o.startsWith(`/`)?this.runCommand(e):!s&&qm(e)?this.runShell(e):await this.deliverPromptToSession(a,e,t,n,r,R(this.getState()),{markSending:s})}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:rg(n,e)})}async runShell(e){let t=this.getState().selectedSession;return!t||t.archived===!0?!1:cg(t)?this.enqueuePendingSessionSend(t,{type:`shell`,text:e}):await this.deliverShellToSession(t,e,R(this.getState()),{optimisticLine:!0})}async runCommand(e){let t=this.getState().selectedSession;return!t||t.archived===!0?!1:cg(t)?this.enqueuePendingSessionSend(t,{type:`command`,text:e}):await this.deliverCommandToSession(t,e,R(this.getState()),{applyResult:!0})}async renameSession(e,t){if(e.archived===!0||cg(e))return;let n=t.trim();if(n===``)return;let r=R(this.getState());try{let t=await this.api.runCommand(e,`/name ${n}`,r);if(R(this.getState())!==r)return;if(t.type===`done`&&t.session!==void 0){this.applySessionName(t.session.id,t.session.name);return}this.setState({error:t.type===`unsupported`?t.message:`Could not rename session.`})}catch(e){R(this.getState())===r&&this.setState({error:String(e)})}}enqueuePendingSessionSend(e,t,n){let r=this.pendingSessionStarts.get(e.id);if(r===void 0||r.discarded)return this.setState({error:`The backend session is not ready for queued sends. Copy your message before discarding this failed start.`}),!1;let i={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`,...n===void 0?{}:{onDelivered:n}};r.queuedSends.push(i);let a=this.getState(),o=a.clientQueuedSessionMessages[e.id]??[],s=lg(e.id,r.queuedSends.length);return this.setState({clientQueuedSessionMessages:{...a.clientQueuedSessionMessages,[e.id]:[...o,dg(i)]},sessionActivities:{...a.sessionActivities,[e.id]:s},activity:a.selectedSession?.id===e.id?s:a.activity,error:``}),!0}async flushQueuedPendingSends(e,t,n){for(let r=0;r<n.length;r+=1){let i=n[r];if(i===void 0)continue;let a=await this.deliverQueuedPendingSend(e,t,i);if(i.onDelivered?.(a),!a){for(let e of n.slice(r+1))e.onDelivered?.(!1);return}this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,t,{markSending:!0}):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0}):this.deliverCommandToSession(e,n.text,t,{applyResult:!0})}async deliverPromptToSession(e,t,n,r,i,a,o){let s=r!==void 0&&r.length>0;o.markSending&&this.markSendingPrompt(e.id,!0);try{if(s&&i===`folder`){let i=(await this.api.saveAttachments(e,r,a)).map(e=>Vm(e.path,!1)).join(` `),o=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,o,n,a)}else await this.api.prompt(e,t,n,a,r);return this.markCachedNewSessionPersisted(e),!0}catch(e){return this.setState({error:String(e)}),!1}finally{o.markSending&&this.markSendingPrompt(e.id,!1)}}async deliverShellToSession(e,t,n,r){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,tp(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,tp(`system`,String(t))]}),this.setState({error:String(t)}),!1}}async deliverCommandToSession(e,t,n,r){this.markSendingPrompt(e.id,!0);try{let i=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?this.applyCommandResult(i):(i.type===`select`||i.type===`tree`)&&this.setState({error:`Queued command “${t}” needs input; open the session and run it again.`}),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,tp(`system`,String(t))]}),this.setState({error:String(t)}),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?rg(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(n){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(n,e,t,R(this.getState())))}catch(e){this.setState({error:String(e)})}}}cancelCommand(){this.setState({commandDialog:void 0})}async navigateTree(e,t){let n=this.getState(),r=n.selectedSession,i=n.treeDialog;if(r===void 0||i===void 0||r.archived===!0||cg(r))throw Error(`The session tree navigator is no longer available`);let a=R(n),o=this.selectionSeq,s;try{s=await this.api.navigateTree(r,{targetId:e,expectedLeafId:i.activeLeafId,summary:t},a)}catch(e){throw this.isCurrentSessionSelection(r.id,a,o)&&this.setState({error:String(e)}),e}return s.cancelled||await this.refreshAfterTreeNavigation(r,a,s.editorText??``,i),s}async editFromHere(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||cg(r))throw Error(`The message action is no longer available`);let i=R(n),a=this.selectionSeq,o;try{o=await this.api.editFromHere(r,e,i)}catch(e){throw this.isCurrentSessionSelection(r.id,i,a)&&this.setState({error:String(e)}),e}return o.cancelled||await this.refreshAfterTreeNavigation(r,i,t),o}async forkFromHere(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||n.archived===!0||cg(n))return;let r=R(t),i=this.selectionSeq,a;try{a=await this.api.forkFromHere(n,e,r)}catch(e){this.isCurrentSessionSelection(n.id,r,i)&&this.setState({error:String(e)});return}if(a.cancelled)return;let o=this.getState();if(R(o)!==r)return;let s=[a.session,...o.sessions.filter(e=>e.id!==a.session.id)];this.setState({sessions:s}),this.isCurrentSessionSelection(n.id,r,i)&&await this.selectSession(a.session)}async refreshAfterTreeNavigation(e,t,n,r){let i=xd(t,e.id);if(Ip(i,n),this.transcripts.discard(i),!this.isSelectedSessionIdentity(e.id,t))return;this.clearPendingUpdates();let a;try{await this.selectSession(e,{updateUrl:!1,...r===void 0?{}:{preserveTreeDialog:!0},propagateRefreshError:!0})}catch(e){a={error:e}}if(this.isSelectedSessionIdentity(e.id,t)){try{await this.replacePromptEditorText?.({machineId:t,sessionId:e.id,text:n})}catch(n){throw this.isSelectedSessionIdentity(e.id,t)&&this.setState({error:String(n)}),n}if(a!==void 0)throw this.isSelectedSessionIdentity(e.id,t)&&this.setState({error:String(a.error)}),a.error;r!==void 0&&this.isSelectedSessionIdentity(e.id,t)&&this.getState().treeDialog===r&&this.setState({treeDialog:void 0})}}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||cg(t))return;let n=R(e),r=this.selectionSeq;try{await this.api.abort(t,n)}catch(e){throw this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)}),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e),n=this.sessionPersistenceOptions();if(wh(e,t,n)){await this.deleteCachedNewSession(e);return}if(Ch(e,t,n))try{await this.api.archive(e,R(this.getState()));let t=this.getState(),n=Lh(t.sessions,e.id,new Date().toISOString()),r=zh(n,t.selectedSession?.id,e.id);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(!(e===void 0||!Ch(e,this.statusForSession(e),this.sessionPersistenceOptions())))try{let t=await this.api.archiveWithDescendants(e,R(this.getState())),n=t.sessionIds!==void 0&&t.sessionIds.length>0?t.sessionIds:[e.id],r=this.getState(),i=Rh(r.sessions,n,new Date().toISOString()),a=Bh(i,r.selectedSession?.id,n);this.setState({sessions:i}),a.type===`select`?await this.selectSession(a.session):a.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessions(e){let t=this.sessionPersistenceOptions(),n=mg(e).filter(e=>Ch(e,this.statusForSession(e),t));if(n.length!==0)try{let e=R(this.getState()),{succeededIds:t,failures:r,generatedAt:i}=await this.archiveSessionBatch(n,e);if(t.length>0){let e=this.getState(),n=Rh(e.sessions,t,i??new Date().toISOString()),r=Bh(n,e.selectedSession?.id,t);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures(`Archive`,r)}catch(e){this.setState({error:`Archive failed: ${xg(e)}`})}}async deleteArchivedSessions(e){let t=mg(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=R(this.getState()),r=this.getState().machineRuntimes[n];if(r?.ok===!0&&!E(r,w.sessionsDeleteArchived)){this.setState({error:`Deleting archived sessions requires an updated Pi-Web runtime on this machine.`});return}try{let{succeededIds:e,failures:r}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let t=new Set(e),n=this.getState(),r=n.sessions.filter(e=>!t.has(e.id));if(this.setState({sessions:r}),n.selectedSession!==void 0&&t.has(n.selectedSession.id)){let e=r.find(e=>e.archived!==!0)??r[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}}this.applyBulkSessionFailures(`Delete`,r)}catch(e){this.setState({error:`Delete failed: ${xg(e)}`})}}async archiveSessionBatch(e,t){let n=this.getState().machineRuntimes[t];if(n?.ok===!0&&E(n,w.sessionsBulkMutations)){let n=await this.api.archiveMany(e,t);return{succeededIds:n.archivedSessionIds,failures:gg(n.failures),generatedAt:n.generatedAt}}let r=await vg(e,qh,async e=>(await this.api.archive(e,t),e.id));return{succeededIds:hg(r),failures:_g(e,r)}}async deleteArchivedSessionBatch(e,t){let n=this.getState().machineRuntimes[t];if(n?.ok===!0&&E(n,w.sessionsBulkMutations)){let n=await this.api.deleteArchivedMany(e,t);return{succeededIds:n.deletedSessionIds,failures:gg(n.failures)}}let r=await vg(e,qh,async e=>(await this.api.deleteArchived(e,t),e.id));return{succeededIds:hg(r),failures:_g(e,r)}}async applySessionCleanupResult(e,t=R(this.getState())){if(R(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=Rh(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);if(this.setState({sessions:o,sessionStatuses:ig(t.sessionStatuses,a),sessionActivities:ig(t.sessionActivities,a),...s?{status:void 0,activity:void 0}:{}}),t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=o.find(e=>e.archived!==!0)??o[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}else{let e=Bh(o,t.selectedSession?.id,n);e.type===`select`?await this.selectSession(e.session):e.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(t)}async refreshCurrentWorkspaceSessions(e=R(this.getState())){let t=this.getState().selectedWorkspace;if(t!==void 0)try{let n=Uf(t.path,await this.api.sessions(t.path,e),e).filter(t=>!this.isSuppressedCreatedSession(t,e));if(R(this.getState())!==e||this.getState().selectedWorkspace?.id!==t.id)return;let r=this.mergePendingStartSessions(t.path,n,e),i=this.getState().selectedSession;if(this.setState({sessions:r}),i===void 0)return;let a=r.find(e=>e.id===i.id);if(a!==void 0){a!==i&&this.setState({selectedSession:a});return}let o=r.find(e=>e.archived!==!0)??r[0];o===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(o)}catch(n){R(this.getState())===e&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(n)})}}async reorderSession(e,t){if(this.sessionReorderInFlight||e.archived===!0||e.persisted!==!0)return;let n=this.getState(),r=R(n),i=n.selectedWorkspace?.id,a=this.selectionSeq,o=t.orderedSessions.map((e,t)=>({...e,manualOrder:t})),s=Cg(n.sessions,t.orderedSessions),c=Cg(n.projectSessions,t.orderedSessions),l=Cg(n.selectedSession===void 0?[]:[n.selectedSession],t.orderedSessions);this.sessionReorderInFlight=!0,this.setState({sessions:Sg(n.sessions,o),projectSessions:Sg(n.projectSessions,o),selectedSession:n.selectedSession===void 0?void 0:Sg([n.selectedSession],o)[0]});try{let n=await this.api.reorder(e,t,r);if(!this.isCurrentSessionOrderScope(r,i,a))return;let o=this.getState();this.setState({sessions:Sg(o.sessions,n.orderedSessions),projectSessions:Sg(o.projectSessions,n.orderedSessions),selectedSession:o.selectedSession===void 0?void 0:Sg([o.selectedSession],n.orderedSessions)[0]})}catch(e){if(!this.isCurrentSessionOrderScope(r,i,a))return;let t=this.getState();this.setState({sessions:wg(t.sessions,s),projectSessions:wg(t.projectSessions,c),selectedSession:t.selectedSession===void 0?void 0:wg([t.selectedSession],l)[0],error:`Reorder failed: ${xg(e)}`}),await Promise.allSettled([this.refreshCurrentWorkspaceSessions(r),Promise.resolve().then(()=>this.refreshProjectSessionCatalog())])}finally{this.sessionReorderInFlight=!1}}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!wh(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=cg(e)?this.pendingSessionStarts.get(e.id):void 0;if(t!==void 0){t.discarded=!0;for(let e of t.queuedSends)e.onDelivered?.(!1);t.queuedSends=[]}else this.api.stop(e,R(this.getState())).catch(()=>{});Hf(e.id,R(this.getState())),Lp(this.sessionCacheKey(e.id)),this.attachmentDrafts.clear(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:rg(n.sessionStatuses,e.id),sessionActivities:$h(n.sessionActivities,e.id),sendingPrompts:rg(n.sendingPrompts,e.id),clientQueuedSessionMessages:rg(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=r.find(e=>e.archived!==!0)??r[0];i===void 0?(this.clearActiveSession(),this.updateUrl()):await this.selectSession(i)}async restoreSession(e=this.getState().selectedSession){if(e)try{await this.api.restore(e,R(this.getState()));let t={...e};delete t.archived,delete t.archivedAt,this.replaceSession(t),this.getState().selectedSession?.id===t.id&&await this.selectSession(t)}catch(e){this.setState({error:String(e)})}}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!Ch(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=R(this.getState()),n=this.getState().machineRuntimes[t];if(n?.ok!==!0||!E(n,w.sessionsReload)){this.setState({error:`Reloading sessions from disk requires an updated Pi-Web runtime on this machine.`});return}try{await this.api.reloadSession(e.id,t),this.transcripts.discard(this.sessionCacheKey(e.id)),this.getState().selectedSession?.id===e.id&&await this.selectSession(e,{updateUrl:!1})}catch(e){this.setState({error:String(e)})}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath!==void 0)try{await this.api.detachParent(e,R(this.getState()));let t={...e};delete t.parentSessionPath,delete t.manualOrder,this.replaceSession(t)}catch(e){this.setState({error:String(e)})}}async pinSession(e=this.getState().selectedSession){if(!(!e||e.archived===!0))try{let t=await this.api.pin(e,R(this.getState()));this.replaceSession(t)}catch(e){this.setState({error:String(e)})}}async unpinSession(e=this.getState().selectedSession){if(!(!e||e.archived===!0))try{let t=await this.api.unpin(e,R(this.getState()));this.replaceSession(t)}catch(e){this.setState({error:String(e)})}}async loadModelPolicy(){let e=this.selectedModelPolicyTarget();if(e===void 0)return;let{session:t,machineId:n,selectionSeq:r}=e,i=++this.modelPolicyIssueSeq;this.modelPolicyLoadSeq=i;let a=this.modelPolicySettledSaveSeq;this.modelPolicySavesInFlight.size>0?this.setState({isLoadingModelPolicy:!0}):this.setState({modelPolicy:void 0,modelPolicyError:void 0,isLoadingModelPolicy:!0});try{let e=await this.api.modelPolicy(t,n);this.canWriteModelPolicyReadResult(t.id,n,r,i,a)&&this.applyConfirmedModelPolicyResponse(e)}catch(e){this.canWriteModelPolicyReadResult(t.id,n,r,i,a)&&this.setState({modelPolicyError:String(e)})}finally{!this.disposed&&this.modelPolicyLoadSeq===i&&this.setState({isLoadingModelPolicy:!1})}}async saveModelPolicy(e){let t=this.selectedModelPolicyTarget();if(t===void 0)return;let{session:n,sessionInfo:r,machineId:i,selectionSeq:a}=t,o=++this.modelPolicyIssueSeq;this.modelPolicySaveSeq=o,this.modelPolicySavesInFlight.add(o),this.setState({modelPolicyError:void 0,isSavingModelPolicy:!0});try{let t=await this.api.setModelPolicy(n,e,i);this.canWriteModelPolicyWriteResult(n.id,i,a,o)&&(this.applyConfirmedModelPolicyResponse(t),tg(r)&&t.policy!==void 0&&t.session.modelPolicy?.blockedReason===void 0&&this.publishStarterModelPolicyConfirmed({reason:`policy-save`,machineId:i,session:{...r},policy:eg(t.policy)}))}catch(e){this.canWriteModelPolicyWriteResult(n.id,i,a,o)&&this.setState({modelPolicyError:String(e)})}finally{this.modelPolicySavesInFlight.delete(o);let e=this.isCurrentSessionSelection(n.id,i,a);e&&o>this.modelPolicySettledSaveSeq&&(this.modelPolicySettledSaveSeq=o),!this.disposed&&this.modelPolicySaveSeq===o&&this.setState({isSavingModelPolicy:!1});let t=e?this.getState().status:void 0;t!==void 0&&this.invalidateSupersededModelPolicy(t)}}selectedModelPolicyTarget(){let e=this.getState(),t=e.selectedSession;if(!(t===void 0||t.archived===!0||cg(t)))return{session:{id:t.id,cwd:t.cwd},sessionInfo:{...t},machineId:R(e),selectionSeq:this.selectionSeq}}canWriteModelPolicyReadResult(e,t,n,r,i){return r!==this.modelPolicyLoadSeq||this.modelPolicySavesInFlight.size>0||this.modelPolicySettledSaveSeq!==i?!1:this.isCurrentSessionSelection(e,t,n)}canWriteModelPolicyWriteResult(e,t,n,r){return r===this.modelPolicySaveSeq&&this.isCurrentSessionSelection(e,t,n)}publishStarterModelPolicyConfirmed(e){try{this.onStarterModelPolicyConfirmed?.(e)}catch{}}captureStarterModelPolicySubstitution(e,t,n){if(this.starterModelPolicySubstitutionChecks.has(e.id))return;let r={machineId:t,session:{...e},requestedPolicy:eg(n),observed:!1};this.starterModelPolicySubstitutionChecks.set(e.id,r);let i=this.getState().sessionStatuses[e.id];i!==void 0&&this.runStarterPolicySubstitutionCheck(e.id,i)}plusPendingStartPolicy(e,t){for(let n of this.pendingSessionStarts.values())if(n.cwd===e&&n.machineId===t&&!n.discarded&&n.request.kind===`plus`)return n.request.initialModelPolicy}runStarterPolicySubstitutionCheck(e,t){let n=this.starterModelPolicySubstitutionChecks.get(e);if(n===void 0||n.observed)return;let r=t.modelPolicy;if(r===void 0)return;n.observed=!0;let i=n.requestedPolicy;if(!(i.mode===`exact`?r.mode!==`exact`||!Du(r.resolved,i.exact):r.mode===`exact`))return;let a={machineId:n.machineId,session:{...n.session},requestedPolicy:eg(i),confirmed:{mode:r.mode,resolved:{model:{...r.resolved.model},thinkingLevel:r.resolved.thinkingLevel}}};try{this.onStarterModelPolicySubstitution?.(a)}catch{}}applyConfirmedModelPolicyResponse(e){this.flushPendingUpdates(),this.modelPolicyConfirmedStatus=e.session.modelPolicy,this.setState({modelPolicy:e,modelPolicyError:void 0}),this.applyStatus(e.session)}invalidateSupersededModelPolicy(e){let t=this.getState();t.selectedSession?.id===e.sessionId&&(t.modelPolicy===void 0||e.modelPolicy===void 0||this.modelPolicyConfirmedStatus!==void 0&&(this.modelPolicySavesInFlight.size>0||ng(e.modelPolicy,this.modelPolicyConfirmedStatus)||(this.setState({modelPolicy:void 0}),this.loadModelPolicy())))}clearSelectedModelPolicyState(){return this.modelPolicyLoadSeq=0,this.modelPolicySaveSeq=0,this.modelPolicySettledSaveSeq=0,this.modelPolicySavesInFlight.clear(),this.modelPolicyConfirmedStatus=void 0,{modelPolicy:void 0,isLoadingModelPolicy:!1,isSavingModelPolicy:!1,modelPolicyError:void 0}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.models(e,R(this.getState()))).models}catch(e){return this.setState({error:String(e)}),[]}}async setModel(e,t){let n=this.getState().selectedSession;if(!(!n||n.archived===!0))try{this.applyStatus(await this.api.setModel(n,e,t,R(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async cycleModel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleModel(t,e,R(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.thinkingLevels(e,R(this.getState()))).levels}catch(e){return this.setState({error:String(e)}),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let t=await this.listThinkingLevels();this.getState().selectedSession?.id===e.id&&this.setState({availableThinkingLevels:t})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(t,e,R(this.getState())))}catch(e){this.setState({error:String(e)})}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!(!e||e.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(e,R(this.getState())))}catch(e){this.setState({error:String(e)})}}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||cg(t))return;let n=R(e),r=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,r)&&this.applyStatus(e)}catch(e){this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)})}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||cg(n))return;let r=R(t),i=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,i)&&this.applyStatus(t)}catch(e){this.isCurrentSessionSelection(n.id,r,i)&&this.setState({error:String(e)})}}async stopActiveWork(){let e=this.getState().selectedSession;if(e)try{await this.api.abort(e,R(this.getState()))}catch(e){this.setState({error:String(e)})}}refreshSelectedSession(e=this.getState().selectedSession?.id){let t=this.selectedSessionRefreshTarget(e);return t===void 0?Promise.resolve():this.refreshSelectedSessionTarget(t)}selectedSessionRefreshTarget(e){let t=this.getState().selectedSession;if(!(e===void 0||t?.id!==e||t.archived===!0||cg(t)))return{session:t,machineId:R(this.getState()),selectionSeq:this.selectionSeq}}refreshSelectedSessionTarget(e){return this.requestSelectedSessionRefresh(e).catch(t=>{Uh(t)||this.isCurrentRefreshTarget(e)&&this.setState({error:String(t)})})}requestSelectedSessionRefresh(e){let t=xd(e.machineId,e.session.id);return this.selectedSessionRefreshes.request(t,async()=>{if(!this.isCurrentRefreshTarget(e))return;this.flushPendingUpdates();let n=this.selectionLoad.signal,r=this.extensionStreamGeneration,[i,a,o,s]=await Promise.all([this.api.messages(e.session,{limit:Gh},e.machineId,n),this.api.status(e.session,e.machineId,n),this.api.streamSnapshot(e.session,e.machineId,n).catch(e=>{if(Uh(e))throw e;return{seq:0,partial:null}}),this.api.extensionEntries(e.session,e.machineId,n).catch(e=>{if(Uh(e))throw e;return{entries:[],seq:void 0,readRevision:void 0}}),this.notifications?.refreshSelectedSession(e.session,e.machineId)??Promise.resolve()]);if(!this.isCurrentRefreshTarget(e))return;let c=this.transcripts.mergeHistory(t,i),l=this.transcripts.seedStreamingPartial(c.messages,o.partial);this.streamWatermark={sessionId:e.session.id,seq:o.seq};let u=r===this.extensionStreamGeneration?this.applyExtensionSnapshot(e.session.id,s):{};this.setState({...c,messages:l,status:a,...u,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(a)})}applyExtensionSnapshot(e,t){let n=t.seq;if(n===void 0||t.readRevision===void 0)return{};let r=this.extensionReadRevision;if(r?.sessionId===e&&t.readRevision<r.revision)return{};let i=(this.extensionJournal?.sessionId===e?this.extensionJournal.events:[]).filter(e=>e.seq!==void 0&&e.seq>n).sort((e,t)=>(e.seq??0)-(t.seq??0)),a=t.entries;for(let e of i)a=Xh(a,e.entry);return this.extensionCursor={sessionId:e,seq:n},this.extensionReadRevision={sessionId:e,revision:t.readRevision},this.extensionJournal={sessionId:e,events:i},{sessionExtensionEntries:a}}applyExtensionEntryEvent(e){let t=this.getState().selectedSession;if(t===void 0)return;let n=this.extensionCursor;if(e.seq!==void 0&&n?.sessionId===t.id&&e.seq<=n.seq||(this.applySessionExtensionEntry(e.entry),e.seq===void 0))return;let r=this.extensionJournal?.sessionId===t.id?this.extensionJournal.events:[];r.push(e),r.length>this.maxJoinBufferedEvents&&r.splice(0,r.length-this.maxJoinBufferedEvents),this.extensionJournal={sessionId:t.id,events:r}}resetExtensionBaseline(){this.extensionCursor=void 0,this.extensionReadRevision=void 0,this.extensionJournal=void 0,this.extensionStreamGeneration+=1}async refreshSelectedExtensionEntries(){let e=this.getState().selectedSession;if(e===void 0||e.archived===!0||cg(e))return;let t=R(this.getState()),n=this.extensionStreamGeneration;try{let r=await this.api.extensionEntries(e,t,this.selectionLoad.signal);if(n!==this.extensionStreamGeneration||!this.isSelectedSessionIdentity(e.id,t))return;this.setState(this.applyExtensionSnapshot(e.id,r))}catch(e){if(Uh(e))return}}isCurrentRefreshTarget(e){return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)}isCurrentSessionSelection(e,t,n){return this.isCurrentHistoryTarget(e,t,n)&&this.isSelectedSessionIdentity(e,t)}isCurrentHistoryTarget(e,t,n){if(this.disposed||n!==this.selectionSeq)return!1;let r=this.getState();return R(r)===t&&r.selectedSession?.id===e}isCurrentSessionOrderScope(e,t,n){let r=this.getState();return!this.disposed&&n===this.selectionSeq&&R(r)===e&&r.selectedWorkspace?.id===t}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return R(n)===t&&r?.id===e&&r.archived!==!0&&!cg(r)}applyBulkSessionFailures(e,t){t.length!==0&&this.setState({error:`${e} failed for ${String(t.length)} session${t.length===1?``:`s`}: ${t.join(`; `)}`})}sessionCacheKey(e){return xd(R(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}sessionPersistenceOptions(){let e=this.getState();return xh(e.machineRuntimes[R(e)])}workspaceSelectionKey(e){return`${R(this.getState())}:${e}`}replaceSession(e){let t=this.getState(),n=t.selectedSession;this.setState({sessions:t.sessions.map(t=>t.id===e.id?e:t),projectSessions:t.projectSessions.map(t=>t.id===e.id?e:t),selectedSession:n?.id===e.id?e:n})}createPendingSessionStart(e,t,n){let r=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,i=new Date().toISOString(),a=n.kind===`plus`?{kind:`plus`,initialModelPolicy:eg(n.initialModelPolicy)}:n,o={id:r,path:`pi-webui://pending-session/${r}`,cwd:e.path,persisted:!1,name:`New session`,created:i,modified:i,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t,...a.kind===`plus`?{creationSource:`session-list-plus`}:{}};return{tempId:r,workspaceId:e.id,cwd:e.path,machineId:t,session:o,queuedSends:[],discarded:!1,request:a}}insertAndSelectPendingSession(e){let t=this.getState();this.selectClientPendingStartSession(e,{activity:lg(e.id),sessions:[e,...t.sessions.filter(t=>t.id!==e.id)]})}selectClientPendingStartSession(e,t){this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.selectionLoad.abort(),this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:lg(e.id,r.queuedSends.length));this.setState({...t?.sessions===void 0?{}:{sessions:t.sessions},selectedSession:e,messages:[],sessionExtensionEntries:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,availableThinkingLevels:[],...this.clearSelectedModelPolicyState(),treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return!1;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){for(let e of r)e.onDelivered?.(!1);return Lp(xd(n.machineId,e)),this.attachmentDrafts.clear(xd(n.machineId,e)),this.setState({clientQueuedSessionMessages:rg(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{}),!1}n.request.kind===`plus`&&this.captureStarterModelPolicySubstitution(t,n.machineId,n.request.initialModelPolicy),Bf(t,n.machineId),Rp(xd(n.machineId,e),xd(n.machineId,t.id)),this.attachmentDrafts.move(xd(n.machineId,e),xd(n.machineId,t.id));let a=Vf(t,n.machineId);if(!this.isCurrentPendingStart(n))return this.setState({clientQueuedSessionMessages:rg(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r),!1;let o=this.getState(),s=o.selectedSession?.id===e;return this.setState({sessions:sg(o.sessions,e,a),sessionActivities:$h(o.sessionActivities,e),sendingPrompts:ag(o.sendingPrompts,e,a.id),clientQueuedSessionMessages:ag(o.clientQueuedSessionMessages,e,a.id),...s?{selectedSession:a,status:o.sessionStatuses[a.id],activity:o.sessionActivities[a.id]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),s&&(this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1})),await this.flushQueuedPendingSends(a,n.machineId,r),!0}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);for(let e of n.queuedSends)e.onDelivered?.(!1);let r=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),i=this.isCurrentPendingStart(n);if(n.discarded||!i){i&&this.applyReleasedCreatedSessions(r,n.machineId);return}let a=this.getState(),o=xg(t),s=ug(e,o,n.queuedSends.length),c=a.sessions.some(t=>t.id===e);this.setState({sessions:c?a.sessions:[n.session,...a.sessions],sessionActivities:{...a.sessionActivities,[e]:s},activity:a.selectedSession?.id===e?s:a.activity,error:`Failed to start session: ${o}`}),this.applyReleasedCreatedSessions(r,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return R(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd!==e||i.machineId!==t||(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||R(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>cg(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t){try{let n=R(this.getState()),r=await this.api.startSession(e.cwd,n);Bf(r,n),Rp(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),this.attachmentDrafts.move(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),Hf(e.id,n);let i=Vf(r,n);this.setState({sessions:[i,...this.getState().sessions.filter(t=>t.id!==e.id)],error:``}),await this.selectSession(i,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(e){this.setState({error:String(e)})}}markCachedNewSessionPersisted(e){if(!Wf(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Gf(t))}applyCommandResult(e){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let t=(e.type,e.message);if(t!==void 0&&t!==``&&this.setState({messages:[...this.getState().messages,tp(e.type===`unsupported`?`system`:`tool`,t)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&Ip(this.sessionCacheKey(e.session.id),e.promptDraft);let t=this.getState().selectedSession,n=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];this.setState({sessions:n,selectedSession:t?.id===e.session.id?e.session:t}),t?.id!==e.session.id&&this.selectSession(e.session)}}applyCreatedSession(e){let t=this.getState(),n=t.selectedWorkspace?.path===e.cwd||t.workspaces.some(t=>t.path===e.cwd)?og(t.projectSessions,e):t.projectSessions;if(t.selectedWorkspace?.path!==e.cwd){n!==t.projectSessions&&this.setState({projectSessions:n});return}if(t.sessions.some(t=>t.id===e.id)){n!==t.projectSessions&&this.setState({projectSessions:n});return}let r=R(t);if(this.hasPendingStartFor(e.cwd,r)){let i=this.plusPendingStartPolicy(e.cwd,r);i!==void 0&&this.captureStarterModelPolicySubstitution(e,r,i),this.suppressedCreatedSessions.set(e.id,{session:e,machineId:r}),n!==t.projectSessions&&this.setState({projectSessions:n});return}this.setState({sessions:[e,...t.sessions],projectSessions:n})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.sessionActivities[e.sessionId]?.phase===`active`&&!vd(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Eg(t,e.sessionId,e.messageCount),...n?{sessionActivities:$h(t.sessionActivities,e.sessionId)}:{},status:t.selectedSession?.id===e.sessionId?e:t.status,activity:t.selectedSession?.id===e.sessionId&&n?void 0:t.activity}),this.invalidateSupersededModelPolicy(e),this.runStarterPolicySubstitutionCheck(e.sessionId,e)}applySessionExtensionEntry(e){this.setState({sessionExtensionEntries:Xh(this.getState().sessionExtensionEntries,e)})}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession,i=this.getState();this.setState({sessions:i.sessions.map(n),projectSessions:i.projectSessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(R(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(R(this.getState()),e.notificationId)===!0)return;if(e.type===`session.extensionEntry`){this.applyExtensionEntryEvent(e);return}if(e.type===`session.subscribed`){this.refreshSelectedExtensionEntries();return}if(this.isStreamEventBelowWatermark(e))return;if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(lh(e)){this.queueTranscriptEvent(e);return}this.flushPendingUpdates();let t=this.transcripts.applyLiveEvent(this.getState().messages,e);t?this.setState({messages:t}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name),e.type===`agent.end`&&this.refreshSelectedSession()}applyJoinBufferedEvents(e,t){if(e.overflowed){this.requestOverloadResync(t);return}for(let t of e.drain())this.applyEvent(t)}queueTranscriptEvent(e){this.streamEventBuffer.enqueue(e),this.schedulePendingFlush()}pendingTranscriptEventCount(){return this.streamEventBuffer.eventCount}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){let{events:e,resyncRequired:t}=this.streamEventBuffer.drain();if(e.length>0){let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(t&&this.requestOverloadResync(),this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}requestOverloadResync(e=this.selectedSessionRefreshTarget(this.getState().selectedSession?.id)){if(e===void 0||!this.isCurrentRefreshTarget(e))return;let t=this.now(),n=this.lastOverloadResyncAt;if(n!==void 0){let r=t-n;if(r<Kh){this.scheduleDeferredOverloadResync(e,Kh-r);return}}this.cancelPendingOverloadResync(),this.lastOverloadResyncAt=t,this.refreshSelectedSessionTarget(e)}scheduleDeferredOverloadResync(e,t){if(this.pendingOverloadResync!==void 0)return;let n={cancel:()=>void 0};this.pendingOverloadResync=n,n.cancel=this.scheduleOverloadResync(()=>{this.pendingOverloadResync===n&&(this.pendingOverloadResync=void 0,this.requestOverloadResync(e))},t)}cancelPendingOverloadResync(){let e=this.pendingOverloadResync;e!==void 0&&(this.pendingOverloadResync=void 0,e.cancel())}clearPendingUpdates(){this.cancelPendingOverloadResync(),this.streamEventBuffer.clear(),this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}isStreamEventBelowWatermark(e){let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}};function $h(e,t){return rg(e,t)}function eg(e){return{mode:e.mode,exact:{model:{provider:e.exact.model.provider,id:e.exact.model.id},thinkingLevel:e.exact.thinkingLevel},...e.tier===void 0?{}:{tier:e.tier}}}function tg(e){return e.creationSource===`session-list-plus`&&e.parentSessionPath===void 0&&e.archived!==!0}function ng(e,t){return e.mode===t.mode&&e.tier===t.tier&&e.blockedReason===t.blockedReason&&e.resolved.thinkingLevel===t.resolved.thinkingLevel&&e.resolved.model.provider===t.resolved.model.provider&&e.resolved.model.id===t.resolved.model.id}function rg(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function ig(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function ag(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...rg(e,t),[n]:r}}function og(e,t){return e.find(e=>e.id===t.id||e.path===t.path)===t?e:[t,...e.filter(e=>e.id!==t.id&&e.path!==t.path)]}function sg(e,t,n){let r=[],i=!1;for(let a of e){if(a.id===t){i||=(r.push(n),!0);continue}a.id!==n.id&&r.push(a)}return i?r:[n,...r]}function cg(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function lg(e,t=0){return{sessionId:e,phase:`active`,label:`Creating session`,detail:t>0?`${String(t)} queued ${t===1?`message`:`messages`} will send when the backend session is ready`:`Waiting for the backend session to be ready`,at:new Date().toISOString()}}function ug(e,t,n=0){return{sessionId:e,phase:`error`,label:`Session creation failed`,detail:`${t}${n>0?` · ${String(n)} queued ${n===1?`message`:`messages`} kept below`:``}`,at:new Date().toISOString()}}function dg(e){return e.type===`prompt`?{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:fg(e.text,e.attachments)}:{kind:`followUp`,text:e.text}}function fg(e,t){let n=pg(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function pg(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=`${String(n)} ${n===1?`attachment`:`attachments`}`;return t.length===0?`[${r} queued]`:`[${r} queued: ${t.slice(0,3).join(`, `)}${t.length>3?`, +${String(t.length-3)} more`:``}]`}function mg(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function hg(e){return e.filter(yg).map(e=>e.value)}function gg(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function _g(e,t){return t.flatMap((t,n)=>bg(t)?[`${e[n]?.id??`unknown`}: ${xg(t.reason)}`]:[])}async function vg(e,t,n){let r=e.map((e,t)=>({item:e,index:t})),i=[],a=0;async function o(){for(;a<r.length;){let e=r[a];if(e===void 0)return;a+=1;try{i[e.index]={status:`fulfilled`,value:await n(e.item)}}catch(t){i[e.index]={status:`rejected`,reason:t}}}}let s=Math.min(Math.max(1,t),r.length);return await Promise.all(Array.from({length:s},()=>o())),i}function yg(e){return e.status===`fulfilled`}function bg(e){return e.status===`rejected`}function xg(e){return e instanceof Error?e.message:String(e)}function Sg(e,t){let n=new Map(t.map(e=>[Tg(e),e]));return e.map(e=>{let t=n.get(Tg(e));return t===void 0||e.manualOrder===t.manualOrder?e:{...e,manualOrder:t.manualOrder}})}function Cg(e,t){let n=new Set(t.map(Tg));return e.flatMap(e=>n.has(Tg(e))?[{id:e.id,cwd:e.cwd,manualOrder:e.manualOrder}]:[])}function wg(e,t){let n=new Map(t.map(e=>[Tg(e),e]));return e.map(e=>{let t=n.get(Tg(e));if(t===void 0)return e;if(t.manualOrder===void 0){if(!Object.hasOwn(e,`manualOrder`))return e;let{manualOrder:t,...n}=e;return n}return e.manualOrder===t.manualOrder?e:{...e,manualOrder:t.manualOrder}})}function Tg(e){return JSON.stringify([e.cwd,e.id])}function Eg(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.projectSessions.some(e=>e.id===t&&e.messageCount!==n)?e.projectSessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,a=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===void 0?{}:{projectSessions:i},...a===e.selectedSession?{}:{selectedSession:a}}}function Dg(e){return e instanceof Error&&e.message.toLowerCase().includes(`session not found`)}var Og={order:0,overflowWatermark:0};function kg(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Og,optimisticDismissedIds:[],announcements:[]}}function Ag(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&Wg(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function jg(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??kg(t),needsRefresh:!1,changed:!1};if(e===void 0||!Wg(e,t))return{value:Kg(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:Kg(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[];break}let o=i[0]?.order??0;if(!qg(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function Mg(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=Yg(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...Xg(Jg(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function Ng(e){return e===`error`?`Error`:e===`warning`?`Warning`:`Info`}function Pg(e){return`${Ng(e.severity)} notification received.`}function Fg(e){return e.retainedCount+e.discardedCount}function Ig(e){return`Notifications (${String(Fg(e))})`}function Lg(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return`Dismiss ${Ng(e.severity).toLowerCase()} notification`;let n=Array.from(t);return`Dismiss notification: ${n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`}`}function Rg(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function zg(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Bg(e,t){return e.has(zg(t))}function Vg(e,t,n){let r=new Set(e),i=zg(t);return n?r.add(i):r.delete(i),r}function Hg(e){return`${String(e)} older ${e===1?`notification`:`notifications`} not shown.`}function Ug(e){if(!e.truncated)return;let t=Kt/1024;return`Message truncated at ${String(t)} KiB.`}function Wg(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function Gg(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function Kg(e){return{...kg(e),status:`stale`}}function qg(e,t){return e.length===t.retainedCount&&Jg(e)===t.highestSeverity}function Jg(e){let t;for(let n of e)t=Gg(t,n.severity);return t}function Yg(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function Xg(e){return e===void 0?{}:{highestSeverity:e}}var Zg=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.acceptedSupportByMachine=new Set,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??Lc,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.acceptedSupportByMachine.clear(),this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){if(this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0||!this.machineSupportsNotifications(t)){this.setState({selectedNotificationInbox:void 0});return}this.setState({selectedNotificationInbox:kg(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineSupportsNotifications(t)||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;this.acceptedSupportByMachine.add(e);let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=jg(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;e.machines!==t.machines&&this.pruneRemovedMachines(t.machines);let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||e.machineRuntimes!==t.machineRuntimes,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineSupportsNotificationsInState(e,r.machineId)&&this.machineIsReachableInState(e,r.machineId);if(!this.machineSupportsNotifications(r.machineId)||!this.machineIsReachable(r.machineId)){this.markSelectedStale(r);return}this.ensureSelectedProjection(r),(!i||this.getState().selectedNotificationInbox?.status!==`fresh`)&&this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId)}shouldFilterLegacyNotification(e,t){return t!==void 0&&t!==``&&this.machineSupportsNotifications(e)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=Mg(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=Qg(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:`Failed to dismiss notification: ${e_(t)}`}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Mg(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=Qg(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:`Failed to dismiss session notifications: ${e_(e)}`}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineSupportsNotifications(t.machineId)||!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}this.acceptedSupportByMachine.add(t.machineId);let i=this.getState().selectedNotificationInbox,a=i===void 0||$g(i,t,r)?Ag(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=jg(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&Wg(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!Wg(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=$g(r,e,t)?Ag(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n===void 0||!Wg(n,e)||this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;(t===void 0||!Wg(t,e))&&this.setState({selectedNotificationInbox:kg(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Wg(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t===void 0||!Wg(t,e)||t.status===`stale`||this.setState({selectedNotificationInbox:{...t,status:`stale`}})}pruneRemovedMachines(e){let t=new Set(e.map(e=>e.id));t.size===0&&t.add(`local`);for(let e of[...this.acceptedSupportByMachine])t.has(e)||this.acceptedSupportByMachine.delete(e)}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Wg(this.selectedTarget,e)}machineSupportsNotifications(e){return this.machineSupportsNotificationsInState(this.getState(),e)}machineSupportsNotificationsInState(e,t){return this.acceptedSupportByMachine.has(t)||e.machineRuntimes[t]?.ok===!0&&E(e.machineRuntimes[t],w.sessionsNotifications)}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function Qg(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function $g(e,t,n){return!Wg(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function e_(e){return e instanceof Error?e.message:String(e)}var t_={available:!1,reason:`Checking OS speech availability.`,voices:[]},n_=5e3,r_=class{constructor(e={}){this.statusValue=a_(t_),this.loadingStatusValue=!1,this.config=Mn(void 0),this.errorClearSequence=0,this.statusRequestSequence=0,this.disposed=!1,this.api=e.api??Zs,this.createRunId=e.createRunId??u_,this.onStateChange=e.onStateChange??(()=>void 0),this.scheduleErrorClear=e.scheduleErrorClear??l_}get snapshot(){return{status:a_(this.statusValue),loadingStatus:this.loadingStatusValue,...this.active===void 0?{}:{active:{runId:this.active.runId,sessionId:this.active.sessionId,messageKey:this.active.messageKey}},...this.errorValue===void 0?{}:{error:this.errorValue}}}configure(e){this.disposed||(this.config=Mn(e))}async refreshStatus(){if(this.disposed)return;let e=++this.statusRequestSequence;this.loadingStatusValue=!0,this.publish();try{let t=await this.api.status();if(!this.isCurrentStatusRequest(e))return;this.statusValue=a_(t)}catch(t){if(!this.isCurrentStatusRequest(e))return;this.statusValue=i_(c_(t))}finally{this.isCurrentStatusRequest(e)&&(this.loadingStatusValue=!1,this.publish())}}select(e){if(this.disposed||o_(this.selection,e))return;this.selection=e===void 0?void 0:{...e};let t=this.clearActive();t!==void 0&&(t.controller.abort(),this.publish(),this.stopAbandoned(t))}async startManual(e){if(this.disposed||!this.canStart(e))return;let t=Nn(e.text);if(t===``)return;let n=this.clearActive();n!==void 0&&(n.controller.abort(),this.stopAbandoned(n));let r=this.createRunId(),i={runId:r,machineId:e.machineId,sessionId:e.sessionId,messageKey:e.messageKey,text:t,controller:new AbortController,requestClosed:!1};this.active=i,this.clearRetryableError(),this.publish();let a=this.config.voice,o={runId:r,text:t,...a!==void 0&&this.statusValue.voices.some(e=>e.name===a)?{voice:a}:{},rate:this.config.rate};try{let e=await this.api.speak(o,i.controller.signal);if(i.requestClosed=!0,!this.isActive(i)||e.runId!==i.runId)return;this.active=void 0,this.publish()}catch(e){if(i.requestClosed=!0,!this.isActive(i))return;if(s_(e)){this.active=void 0,this.publish();return}if(this.active=void 0,e instanceof Qt&&e.status===503){this.statusValue=i_(e.message),this.clearRetryableError(),this.publish();return}this.applyRetryableError(c_(e)),this.publish(),e instanceof Qt&&e.status===500&&this.refreshStatus()}}matchesActiveSource(e){let t=this.active;return t?.sessionId===e.sessionId&&t.messageKey===e.messageKey&&t.text===e.text}async stop(){if(this.disposed)return;let e=this.clearActive();e!==void 0&&(e.controller.abort(),this.publish(),await this.stopActive(e))}dispose(){if(this.disposed)return;this.disposed=!0,this.statusRequestSequence+=1,this.clearError?.(),this.clearError=void 0;let e=this.clearActive();e!==void 0&&(e.controller.abort(),Promise.resolve().then(()=>this.api.stop(e.runId)).catch(()=>void 0))}canStart(e){let t=this.selection;return t?.machineId===`local`&&t.machineId===e.machineId&&t.sessionId===e.sessionId&&this.statusValue.available}clearActive(){let e=this.active;return this.active=void 0,e}isActive(e){return!this.disposed&&this.active===e}isCurrentStatusRequest(e){return!this.disposed&&e===this.statusRequestSequence}async stopAbandoned(e){try{await this.api.stop(e.runId)}catch{}}async stopActive(e){try{await this.api.stop(e.runId)}catch(t){if(await Promise.resolve(),this.disposed||e.requestClosed)return;this.applyRetryableError(c_(t)),this.publish()}}applyRetryableError(e){this.clearError?.(),this.errorValue=e;let t=++this.errorClearSequence;this.clearError=this.scheduleErrorClear(()=>{this.disposed||t!==this.errorClearSequence||(this.errorValue=void 0,this.clearError=void 0,this.publish())},n_)}clearRetryableError(){this.clearError?.(),this.errorClearSequence+=1,this.clearError=void 0,this.errorValue=void 0}publish(){this.disposed||this.onStateChange()}};function i_(e){return{available:!1,reason:e.trim()===``?`Host speech is unavailable.`:e,voices:[]}}function a_(e){return{available:e.available,...e.reason===void 0?{}:{reason:e.reason},voices:e.voices.map(e=>({...e}))}}function o_(e,t){return e?.machineId===t?.machineId&&e?.sessionId===t?.sessionId}function s_(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`}function c_(e){return e instanceof Error?e.message:String(e)}function l_(e,t){let n=globalThis.setTimeout(e,t);return()=>{globalThis.clearTimeout(n)}}function u_(){let e=globalThis.crypto;if(typeof e.randomUUID==`function`)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));return`r${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function d_(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var f_=d_();function p_(e){f_=e}var m_={exec:()=>null};function h_(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function B(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(__.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var g_=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),__={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:h_(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:h_(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:h_(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:h_(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:h_(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:h_(e=>RegExp(`^ {0,${e}}>`))},v_=/^(?:[ \t]*(?:\n|$))+/,y_=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,b_=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,x_=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,S_=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,C_=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,w_=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,T_=B(w_).replace(/bull/g,C_).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),E_=B(w_).replace(/bull/g,C_).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),D_=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,O_=/^[^\n]+/,k_=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,A_=B(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,k_).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),j_=B(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,C_).getRegex(),M_=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,N_=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,P_=B(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,N_).replace(`tag`,M_).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),F_=e=>B(D_).replace(`hr`,x_).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,M_).getRegex(),I_=F_(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),L_=F_(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),R_={blockquote:B(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,L_).getRegex(),code:y_,def:A_,fences:b_,heading:S_,hr:x_,html:P_,lheading:T_,list:j_,newline:v_,paragraph:I_,table:m_,text:O_},z_=B(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,x_).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,M_).getRegex(),B_={...R_,lheading:E_,table:z_,paragraph:B(D_).replace(`hr`,x_).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,z_).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,M_).getRegex()},V_={...R_,html:B(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,N_).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:m_,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:B(D_).replace(`hr`,x_).replace(`heading`,` *#{1,6} *[^
23
23
  ]`).replace(`lheading`,T_).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},H_=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,U_=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,W_=/^( {2,}|\\)\n(?!\s*$)/,G_=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,K_=/[\p{P}\p{S}]/u,q_=/[\s\p{P}\p{S}]/u,J_=/[^\s\p{P}\p{S}]/u,Y_=B(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,q_).getRegex(),X_=/[\p{Pi}\p{Ps}"']/u,Z_=/(?!~)[\p{P}\p{S}]/u,Q_=/(?!~)[\s\p{P}\p{S}]/u,$_=/(?:[^\s\p{P}\p{S}]|~)/u,ev=B(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,g_?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),tv=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,nv=B(tv,`u`).replace(/punct/g,K_).getRegex(),rv=B(tv,`u`).replace(/punct/g,Z_).getRegex(),iv=B(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,`u`).replace(/openQuote/g,X_).replace(/punct/g,K_).getRegex(),av=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,ov=B(av,`gu`).replace(/notPunctSpace/g,J_).replace(/punctSpace/g,q_).replace(/punct/g,K_).getRegex(),sv=B(av,`gu`).replace(/notPunctSpace/g,$_).replace(/punctSpace/g,Q_).replace(/punct/g,Z_).getRegex(),cv=B(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,J_).replace(/punctSpace/g,q_).replace(/punct/g,K_).getRegex(),lv=B(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,J_).replace(/punctSpace/g,q_).replace(/punct/g,K_).getRegex(),uv=B(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,J_).replace(/punctSpace/g,q_).replace(/punct/g,K_).getRegex(),dv=B(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,K_).getRegex(),fv=B(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,J_).replace(/punctSpace/g,q_).replace(/punct/g,K_).getRegex(),pv=B(/\\(punct)/,`gu`).replace(/punct/g,K_).getRegex(),mv=B(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),hv=B(N_).replace(`(?:-->|$)`,`-->`).getRegex(),gv=B(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,hv).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),_v=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,vv=B(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,_v).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),yv=B(/^!?\[(label)\]\[(ref)\]/).replace(`label`,_v).replace(`ref`,k_).getRegex(),bv=B(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,k_).getRegex(),xv=B(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,yv).replace(`nolink`,bv).getRegex(),Sv=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Cv={_backpedal:m_,anyPunctuation:pv,autolink:mv,blockSkip:ev,br:W_,code:U_,del:m_,delLDelim:m_,delRDelim:m_,emStrongLDelim:nv,emStrongRDelimAst:ov,emStrongRDelimUnd:lv,escape:H_,link:vv,nolink:bv,punctuation:Y_,reflink:yv,reflinkSearch:xv,tag:gv,text:G_,url:m_},wv={...Cv,emStrongLDelim:iv,emStrongRDelimAst:cv,emStrongRDelimUnd:uv,link:B(/^!?\[(label)\]\((.*?)\)/).replace(`label`,_v).getRegex(),reflink:B(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,_v).getRegex()},Tv={...Cv,emStrongRDelimAst:sv,emStrongLDelim:rv,delLDelim:dv,delRDelim:fv,url:B(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Sv).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:B(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,Sv).getRegex()},Ev={...Tv,br:B(W_).replace(`{2,}`,`*`).getRegex(),text:B(Tv.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},Dv={normal:R_,gfm:B_,pedantic:V_},Ov={normal:Cv,gfm:Tv,breaks:Ev,pedantic:wv},kv={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},Av=e=>kv[e];function jv(e,t){if(t){if(__.escapeTest.test(e))return e.replace(__.escapeReplace,Av)}else if(__.escapeTestNoEncode.test(e))return e.replace(__.escapeReplaceNoEncode,Av);return e}function Mv(e){try{e=encodeURI(e).replace(__.percentDecode,`%`)}catch{return null}return e}function Nv(e,t){let n=e.replace(__.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(__.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(__.slashPipe,`|`);return n}function Pv(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function Fv(e){let t=e.split(`
24
24
  `),n=t.length-1;for(;n>=0&&__.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
25
25
  `)}function Iv(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function Lv(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Rv(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`),c=e[0].charAt(0)===`!`;r.state.inLink=!0;let l=r.state.linkEmitted,u=r.state.inRawBlock;r.state.linkEmitted=!1;let d=r.inlineTokens(s),f=r.state.linkEmitted;if(r.state.linkEmitted=l,r.state.inLink=!1,!c){if(f){r.state.inRawBlock=u;return}r.state.linkEmitted=!0}return{type:c?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:d}}function zv(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
@@ -1216,7 +1216,7 @@ This will delete every archived session on this machine regardless of age or cle
1216
1216
  .review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1217
1217
  .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; }
1218
1218
  footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
1219
- `]}};H([x({attribute:!1})],AS.prototype,`context`,void 0),H([C(`#workspace-upload-input`)],AS.prototype,`uploadInput`,void 0),H([S()],AS.prototype,`pendingUpload`,void 0),H([S()],AS.prototype,`destinationFolder`,void 0),H([S()],AS.prototype,`overwrite`,void 0),H([S()],AS.prototype,`createDirs`,void 0),H([S()],AS.prototype,`formError`,void 0),H([S()],AS.prototype,`dragActive`,void 0),AS=H([b(`workspace-files-panel`)],AS);function jS(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 MS(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 NS(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function PS(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} · ${qS(t.size)}`}function FS(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function IS(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function LS(e){return e==null?[]:Array.from(e)}function RS(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function zS(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function BS(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 VS(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return GS(e.percent)}}function HS(e){return e.status===`uploading`?e.percent:1}function US(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return GS(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function WS(e){return e.error===void 0?e.response===void 0?`${e.path} · ${qS(e.loaded)} / ${qS(e.total)}`:`Wrote ${e.response.path}`:e.error}function GS(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function KS(){kS(()=>import(`./CodeViewer-CaRR3heo.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function qS(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`${JS(t)} KB`;let n=t/1024;return n<1024?`${JS(n)} MB`:`${JS(n/1024)} GB`}function JS(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var YS=2e3,XS=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)},YS))}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">
1219
+ `]}};H([x({attribute:!1})],AS.prototype,`context`,void 0),H([C(`#workspace-upload-input`)],AS.prototype,`uploadInput`,void 0),H([S()],AS.prototype,`pendingUpload`,void 0),H([S()],AS.prototype,`destinationFolder`,void 0),H([S()],AS.prototype,`overwrite`,void 0),H([S()],AS.prototype,`createDirs`,void 0),H([S()],AS.prototype,`formError`,void 0),H([S()],AS.prototype,`dragActive`,void 0),AS=H([b(`workspace-files-panel`)],AS);function jS(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 MS(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 NS(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function PS(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} · ${qS(t.size)}`}function FS(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function IS(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function LS(e){return e==null?[]:Array.from(e)}function RS(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function zS(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function BS(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 VS(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return GS(e.percent)}}function HS(e){return e.status===`uploading`?e.percent:1}function US(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return GS(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function WS(e){return e.error===void 0?e.response===void 0?`${e.path} · ${qS(e.loaded)} / ${qS(e.total)}`:`Wrote ${e.response.path}`:e.error}function GS(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function KS(){kS(()=>import(`./CodeViewer-DgVx_yzp.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function qS(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`${JS(t)} KB`;let n=t/1024;return n<1024?`${JS(n)} MB`:`${JS(n/1024)} GB`}function JS(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var YS=2e3,XS=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)},YS))}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">
1220
1220
  <p class="error-text">Failed to load system information: ${this.error}</p>
1221
1221
  <button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
1222
1222
  </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">
@@ -1470,7 +1470,7 @@ This will delete every archived session on this machine regardless of age or cle
1470
1470
  <div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
1471
1471
  <unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
1472
1472
  </section>
1473
- `}function lC(){kS(()=>import(`./UnifiedDiffViewer-CM42T5Lo.js`),[],import.meta.url)}function uC(){kS(()=>Promise.resolve().then(()=>RB),void 0,import.meta.url)}function dC(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function fC(e){let t=pC(e);return g`
1473
+ `}function lC(){kS(()=>import(`./UnifiedDiffViewer-BFBQjlJd.js`),[],import.meta.url)}function uC(){kS(()=>Promise.resolve().then(()=>RB),void 0,import.meta.url)}function dC(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function fC(e){let t=pC(e);return g`
1474
1474
  <p class="summary">
1475
1475
  <span class="summary-branch">${t.branch}</span>
1476
1476
  ${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
@@ -2864,7 +2864,7 @@ This will delete every archived session on this machine regardless of age or cle
2864
2864
  `,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(Yk(e.slice(n))!==void 0)return n}}function Jk(e,t){let n=Yk(e);if(n!==void 0)return{type:`latex-display`,raw:n.raw,tex:n.tex,displayMode:!0}}function Yk(e){let t=e.indexOf(`
2865
2865
  `),n=t<0?e:e.slice(0,t),r=Xk(n);if(r===void 0)return;let i=n.slice(r.delimiterEnd).replace(/^[ \t]+/u,``);if(i!==``){let a=Qk(i,r.delimiter);if(a<0)return;let o=i.slice(0,a);if(o.length===0||o.length>Mk)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(`
2866
2866
  `,o),n=t<0?e.length:t,i=e.slice(o,n);if(Zk(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(`
2867
- `)}}if($k(i)||(a.push(i),s+=i.length+ +(a.length>1),s>Mk)||t<0)return;o=t+1}}function Xk(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 Zk(e,t){return RegExp(`^ {0,3}${t===`$$`?`\\$\\$`:`\\\\\\]`}[ \\t]*$`,`u`).test(e)}function Qk(e,t){let n=t===`$$`?`$$`:`\\]`,r=e.slice(0,Mk+n.length),i=0;for(;i<r.length;){let t=r.indexOf(n,i);if(t<0||t>Mk)return-1;if(/^[ \t]*$/u.test(e.slice(t+n.length)))return t;i=t+n.length}return-1}function $k(e){return/^ {0,3}(?:```|~~~)/u.test(e)}function eA(e){return tA(e),e}function tA(e){for(let t of e)nA(t)}function nA(e){if(aA(e,`paragraph`)||aA(e,`heading`)){e.tokens=iA(e.tokens);return}if(aA(e,`blockquote`)){tA(e.tokens);return}if(aA(e,`list`)){for(let t of e.items)tA(t.tokens);return}if(aA(e,`list_item`)){rA(e.tokens);return}if(aA(e,`text`)&&e.tokens!==void 0){e.tokens=iA(e.tokens);return}if(aA(e,`table`)){for(let t of e.header)t.tokens=iA(t.tokens);for(let t of e.rows)for(let e of t)e.tokens=iA(e.tokens)}}function rA(e){for(let t of e)aA(t,`text`)&&t.tokens!==void 0?t.tokens=iA(t.tokens):nA(t)}function iA(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===void 0)break;if(oA(r)){let r=[];for(;n<e.length;){let t=e[n];if(t===void 0||!oA(t))break;r.push(t),n+=1}t.push(...sA(r));continue}(aA(r,`em`)||aA(r,`strong`)||aA(r,`del`)||aA(r,`text`)&&r.tokens!==void 0)&&(r.tokens=iA(r.tokens)),t.push(r),n+=1}return t}function aA(e,t){return e.type===t}function oA(e){return aA(e,`escape`)||aA(e,`text`)&&e.tokens===void 0}function sA(e){let t=e.map(e=>e.raw).join(``);if(!Uk(t))return e;let n=uA(t);if(n.length===0)return e;let r=cA(e),i={index:0},a=[],o=0;for(let e of n){lA(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 lA(a,r,i,o,t.length),a}function cA(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 lA(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 uA(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=mA(r),i=mA(i),a=mA(a),o=mA(o),r!==void 0&&l-r.start-1>Mk&&(fA(t,r.placeholder),r=void 0,s=!0),i!==void 0&&l-i.start-2>Mk&&(fA(t,i.placeholder),i=void 0,c=!0),a!==void 0&&l-a.start-2>Mk&&(a=void 0),o!==void 0&&l-o.start-2>Mk&&(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=dA(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<=Mk&&n.length>0&&n.trim()!==``&&!/\s/u.test(n[0]??``)&&!/\s/u.test(n.at(-1)??``)&&vA(e,a.start)&&yA(e,l+2)&&pA(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<=Mk&&n.length>0&&n.trim()!==``&&pA(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:dA(t,l,l+2,`literal`)};else if(i!==void 0){let n=e.slice(i.start+2,l);n.length<=Mk&&n.trim()!==``?pA(t,i.placeholder,l+2,`literal`):(fA(t,i.placeholder),n.length>Mk&&(c=!0)),i=void 0}}l+=1,n=0;continue}if(!a&&!s)if(r===void 0)gA(e,l)&&(r={start:l,placeholder:dA(t,l,l+1,`literal`)});else{let n=e.slice(r.start+1,l);_A(e,r.start,l,n)?(pA(t,r.placeholder,l+1,`math`,n,!1),r=void 0):(fA(t,r.placeholder),r=void 0,gA(e,l)&&(r={start:l,placeholder:dA(t,l,l+1,`literal`)}))}n=0;continue}n=0}return r!==void 0&&fA(t,r.placeholder),i!==void 0&&fA(t,i.placeholder),SA(hA(t))}function dA(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 fA(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 pA(e,t,n,r,i,a){let o=t.next;for(;o!==void 0&&o.start<n;){let t=o.next;fA(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 mA(e){return e?.placeholder.linked===!0?e:void 0}function hA(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 gA(e,t){let n=e[t+1];return vA(e,t)&&n!==void 0&&!/\s/u.test(n)}function _A(e,t,n,r){return n>t+1&&r.length>0&&!/\s/u.test(r.at(-1)??``)&&yA(e,n+1)}function vA(e,t){if(t<=0)return!0;let n=t-1,r=xA(e.charCodeAt(n))?n-1:n;return bA(e.codePointAt(r))}function yA(e,t){return bA(e.codePointAt(t))}function bA(e){return e===void 0||/[\s\p{P}\p{S}]/u.test(String.fromCodePoint(e))}function xA(e){return e>=56320&&e<=57343}function SA(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 CA(e,t,n){if(e.type===`latex-inline-literal`)return Bk(e.raw);if(e.type===`latex-block-literal`)return`<p>${Bk(e.raw)}</p>`;let r=wA(e);if(r===void 0)return``;if(!TA(r.tex,t))return LA(r);let i;try{i=n(r.tex,{displayMode:r.displayMode})}catch{return LA(r)}if(!EA(i,t))return LA(r);let a=`aria-label="${Vk(r.tex)}"`;return r.displayMode?`<div class="math-display" role="img" ${a}>${i}</div>`:`<span class="math-inline" role="img" ${a}>${i}</span>`}function wA(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 TA(e,t){return t.outputAdmissionClosed||e.length>Nk||t.mathSourceUnits+e.length>Pk||!DA(e)?!1:(t.mathSourceUnits+=e.length,!0)}function EA(e,t){return e.length>zk||t.mathOutputUnits+e.length>Rk?(t.outputAdmissionClosed=!0,!1):(t.mathOutputUnits+=e.length,!0)}function DA(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>Lk)return!1;if(a%2==1){let r=e[t];if(/[A-Za-z@]/u.test(r??``)){n+=1;let r=OA(e,t),a=e.slice(t-1,r);if(kA(a)||!NA(e,a,r))return!1;i=r-1}else i=t}else i=t-1;continue}if(a===`{`){if(t+=1,t>Fk)return!1}else if(a===`}`)t=Math.max(0,t-1);else if(a===`&`&&(r+=1,r>Lk))return!1}return n<=Ik}function OA(e,t){let n=t;for(;n<e.length&&/[A-Za-z@]/u.test(e[n]??``);)n+=1;return n}function kA(e){return[`\\def`,`\\gdef`,`\\edef`,`\\xdef`,`\\let`,`\\newcommand`,`\\renewcommand`,`\\href`,`\\url`,`\\style`,`\\class`,`\\cssId`,`\\bbox`,`\\unicode`,`\\definecolor`].includes(e)}var AA={"\\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}},jA=/^(?:rgb|RGB|gray)$/u,MA=/^[A-Za-z0-9#%(),.!\s-]+$/u;function NA(e,t,n){let r=AA[t];if(r===void 0)return!0;let i=n,a=!1;if(i=FA(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=jA.test(n),i=t+1}for(let t=0;t<r.colorArgs;t+=1){if(i=FA(e,i),e[i]!==`{`)return!1;let t=IA(e,i+1);if(t===-1)return!1;let n=e.slice(i+1,t);if(!a&&!PA(n))return!1;i=t+1}return!0}function PA(e){return e.trim()!==``&&MA.test(e)}function FA(e,t){let n=t;for(;n<e.length&&/\s/u.test(e[n]??``);)n+=1;return n}function IA(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 LA(e){return e.displayMode?`<p>${Bk(e.raw)}</p>`:Bk(e.raw)}var RA=class extends Error{constructor(){super(`MathJax has not finished loading yet`),this.name=`MathJaxNotReadyError`}},zA,BA,VA,HA;function UA(){return zA??=kS(()=>import(`./mathjaxEngine-DNYA4JKZ.js`).then(e=>{VA=e.mathJaxStyles(),HA=WA(VA);let t=document.createElement(`style`);return t.setAttribute(`data-mathjax-chtml`,``),t.textContent=VA,document.head.append(t),BA=e,e}),[],import.meta.url).catch(e=>{throw console.error(`MathJax failed to load; math will render as literal source.`,e),e}),zA}function WA(e){if(!(typeof CSSStyleSheet!=`function`||typeof CSSStyleSheet.prototype.replaceSync!=`function`))try{let t=new CSSStyleSheet;return t.replaceSync(e),t}catch{return}}function GA(e){if(VA===void 0)return;if(HA!==void 0&&`adoptedStyleSheets`in e){e.adoptedStyleSheets.includes(HA)||(e.adoptedStyleSheets=[...e.adoptedStyleSheets,HA]);return}if(e.querySelector(`style[data-mathjax-chtml]`)!==null)return;let t=document.createElement(`style`);t.setAttribute(`data-mathjax-chtml`,``),t.textContent=VA,e.append(t)}function KA(){return BA!==void 0}function qA(){return UA().then(()=>void 0)}function JA(e,t){if(BA===void 0)throw new RA;return BA.convertLatex(e,t.displayMode)}var YA=new V.Renderer;YA.html=({text:e})=>Bk(e);var XA=1600,ZA=6e6,QA=8,$A=new Map,ej=0,tj=JA;function nj(e,t={}){let n=Uk(e),r=t.cache!==!1&&t.renderMath===void 0&&(!n||KA());if(r){let t=$A.get(e);if(t!==void 0)return $A.delete(e),$A.set(e,t),t.html}let i=aj(t.renderMath!==void 0||Uk(e)?Wk(e,t.renderMath??tj):V.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:YA}));return r&&rj(e,i),i}function rj(e,t){let n=e.length+t.length;if(n>ZA/QA)return;let r=$A.get(e);r!==void 0&&($A.delete(e),ej-=r.chars),$A.set(e,{html:t,chars:n}),ej+=n,ij()}function ij(){for(;$A.size>1&&($A.size>XA||ej>ZA);){let e=$A.entries().next();if(e.done===!0)break;let[t,n]=e.value;$A.delete(t),ej-=n.chars}}function aj(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`)&&!oj(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 oj(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}function sj({text:e,live:t}){return t&&(e.length>=24e3||Hk(e))}var cj=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 sj(this)?g`<div class="formatted plain" dir="auto">${this.text}</div>`:g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${jk(this.renderMarkdown())}</div>`}renderMarkdown(){return this.retryMathRender?(this.retryMathRender=!1,nj(this.text,{cache:!1,renderMath:JA})):nj(this.text,{cache:!this.live})}scheduleMathRetry(){this.mathRetryScheduled||KA()||this.live||!Hk(this.text)||(this.mathRetryScheduled=!0,qA().then(()=>{this.retryMathRender=!0,this.requestUpdate()}).catch(()=>{}))}updated(){this.enhanceCodeBlocks(),Hk(this.text)&&this.renderRoot instanceof ShadowRoot&&GA(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 FO(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=[xS,h`
2867
+ `)}}if($k(i)||(a.push(i),s+=i.length+ +(a.length>1),s>Mk)||t<0)return;o=t+1}}function Xk(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 Zk(e,t){return RegExp(`^ {0,3}${t===`$$`?`\\$\\$`:`\\\\\\]`}[ \\t]*$`,`u`).test(e)}function Qk(e,t){let n=t===`$$`?`$$`:`\\]`,r=e.slice(0,Mk+n.length),i=0;for(;i<r.length;){let t=r.indexOf(n,i);if(t<0||t>Mk)return-1;if(/^[ \t]*$/u.test(e.slice(t+n.length)))return t;i=t+n.length}return-1}function $k(e){return/^ {0,3}(?:```|~~~)/u.test(e)}function eA(e){return tA(e),e}function tA(e){for(let t of e)nA(t)}function nA(e){if(aA(e,`paragraph`)||aA(e,`heading`)){e.tokens=iA(e.tokens);return}if(aA(e,`blockquote`)){tA(e.tokens);return}if(aA(e,`list`)){for(let t of e.items)tA(t.tokens);return}if(aA(e,`list_item`)){rA(e.tokens);return}if(aA(e,`text`)&&e.tokens!==void 0){e.tokens=iA(e.tokens);return}if(aA(e,`table`)){for(let t of e.header)t.tokens=iA(t.tokens);for(let t of e.rows)for(let e of t)e.tokens=iA(e.tokens)}}function rA(e){for(let t of e)aA(t,`text`)&&t.tokens!==void 0?t.tokens=iA(t.tokens):nA(t)}function iA(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===void 0)break;if(oA(r)){let r=[];for(;n<e.length;){let t=e[n];if(t===void 0||!oA(t))break;r.push(t),n+=1}t.push(...sA(r));continue}(aA(r,`em`)||aA(r,`strong`)||aA(r,`del`)||aA(r,`text`)&&r.tokens!==void 0)&&(r.tokens=iA(r.tokens)),t.push(r),n+=1}return t}function aA(e,t){return e.type===t}function oA(e){return aA(e,`escape`)||aA(e,`text`)&&e.tokens===void 0}function sA(e){let t=e.map(e=>e.raw).join(``);if(!Uk(t))return e;let n=uA(t);if(n.length===0)return e;let r=cA(e),i={index:0},a=[],o=0;for(let e of n){lA(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 lA(a,r,i,o,t.length),a}function cA(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 lA(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 uA(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=mA(r),i=mA(i),a=mA(a),o=mA(o),r!==void 0&&l-r.start-1>Mk&&(fA(t,r.placeholder),r=void 0,s=!0),i!==void 0&&l-i.start-2>Mk&&(fA(t,i.placeholder),i=void 0,c=!0),a!==void 0&&l-a.start-2>Mk&&(a=void 0),o!==void 0&&l-o.start-2>Mk&&(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=dA(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<=Mk&&n.length>0&&n.trim()!==``&&!/\s/u.test(n[0]??``)&&!/\s/u.test(n.at(-1)??``)&&vA(e,a.start)&&yA(e,l+2)&&pA(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<=Mk&&n.length>0&&n.trim()!==``&&pA(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:dA(t,l,l+2,`literal`)};else if(i!==void 0){let n=e.slice(i.start+2,l);n.length<=Mk&&n.trim()!==``?pA(t,i.placeholder,l+2,`literal`):(fA(t,i.placeholder),n.length>Mk&&(c=!0)),i=void 0}}l+=1,n=0;continue}if(!a&&!s)if(r===void 0)gA(e,l)&&(r={start:l,placeholder:dA(t,l,l+1,`literal`)});else{let n=e.slice(r.start+1,l);_A(e,r.start,l,n)?(pA(t,r.placeholder,l+1,`math`,n,!1),r=void 0):(fA(t,r.placeholder),r=void 0,gA(e,l)&&(r={start:l,placeholder:dA(t,l,l+1,`literal`)}))}n=0;continue}n=0}return r!==void 0&&fA(t,r.placeholder),i!==void 0&&fA(t,i.placeholder),SA(hA(t))}function dA(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 fA(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 pA(e,t,n,r,i,a){let o=t.next;for(;o!==void 0&&o.start<n;){let t=o.next;fA(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 mA(e){return e?.placeholder.linked===!0?e:void 0}function hA(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 gA(e,t){let n=e[t+1];return vA(e,t)&&n!==void 0&&!/\s/u.test(n)}function _A(e,t,n,r){return n>t+1&&r.length>0&&!/\s/u.test(r.at(-1)??``)&&yA(e,n+1)}function vA(e,t){if(t<=0)return!0;let n=t-1,r=xA(e.charCodeAt(n))?n-1:n;return bA(e.codePointAt(r))}function yA(e,t){return bA(e.codePointAt(t))}function bA(e){return e===void 0||/[\s\p{P}\p{S}]/u.test(String.fromCodePoint(e))}function xA(e){return e>=56320&&e<=57343}function SA(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 CA(e,t,n){if(e.type===`latex-inline-literal`)return Bk(e.raw);if(e.type===`latex-block-literal`)return`<p>${Bk(e.raw)}</p>`;let r=wA(e);if(r===void 0)return``;if(!TA(r.tex,t))return LA(r);let i;try{i=n(r.tex,{displayMode:r.displayMode})}catch{return LA(r)}if(!EA(i,t))return LA(r);let a=`aria-label="${Vk(r.tex)}"`;return r.displayMode?`<div class="math-display" role="img" ${a}>${i}</div>`:`<span class="math-inline" role="img" ${a}>${i}</span>`}function wA(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 TA(e,t){return t.outputAdmissionClosed||e.length>Nk||t.mathSourceUnits+e.length>Pk||!DA(e)?!1:(t.mathSourceUnits+=e.length,!0)}function EA(e,t){return e.length>zk||t.mathOutputUnits+e.length>Rk?(t.outputAdmissionClosed=!0,!1):(t.mathOutputUnits+=e.length,!0)}function DA(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>Lk)return!1;if(a%2==1){let r=e[t];if(/[A-Za-z@]/u.test(r??``)){n+=1;let r=OA(e,t),a=e.slice(t-1,r);if(kA(a)||!NA(e,a,r))return!1;i=r-1}else i=t}else i=t-1;continue}if(a===`{`){if(t+=1,t>Fk)return!1}else if(a===`}`)t=Math.max(0,t-1);else if(a===`&`&&(r+=1,r>Lk))return!1}return n<=Ik}function OA(e,t){let n=t;for(;n<e.length&&/[A-Za-z@]/u.test(e[n]??``);)n+=1;return n}function kA(e){return[`\\def`,`\\gdef`,`\\edef`,`\\xdef`,`\\let`,`\\newcommand`,`\\renewcommand`,`\\href`,`\\url`,`\\style`,`\\class`,`\\cssId`,`\\bbox`,`\\unicode`,`\\definecolor`].includes(e)}var AA={"\\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}},jA=/^(?:rgb|RGB|gray)$/u,MA=/^[A-Za-z0-9#%(),.!\s-]+$/u;function NA(e,t,n){let r=AA[t];if(r===void 0)return!0;let i=n,a=!1;if(i=FA(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=jA.test(n),i=t+1}for(let t=0;t<r.colorArgs;t+=1){if(i=FA(e,i),e[i]!==`{`)return!1;let t=IA(e,i+1);if(t===-1)return!1;let n=e.slice(i+1,t);if(!a&&!PA(n))return!1;i=t+1}return!0}function PA(e){return e.trim()!==``&&MA.test(e)}function FA(e,t){let n=t;for(;n<e.length&&/\s/u.test(e[n]??``);)n+=1;return n}function IA(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 LA(e){return e.displayMode?`<p>${Bk(e.raw)}</p>`:Bk(e.raw)}var RA=class extends Error{constructor(){super(`MathJax has not finished loading yet`),this.name=`MathJaxNotReadyError`}},zA,BA,VA,HA;function UA(){return zA??=kS(()=>import(`./mathjaxEngine-CVXA3FNR.js`).then(e=>{VA=e.mathJaxStyles(),HA=WA(VA);let t=document.createElement(`style`);return t.setAttribute(`data-mathjax-chtml`,``),t.textContent=VA,document.head.append(t),BA=e,e}),[],import.meta.url).catch(e=>{throw console.error(`MathJax failed to load; math will render as literal source.`,e),e}),zA}function WA(e){if(!(typeof CSSStyleSheet!=`function`||typeof CSSStyleSheet.prototype.replaceSync!=`function`))try{let t=new CSSStyleSheet;return t.replaceSync(e),t}catch{return}}function GA(e){if(VA===void 0)return;if(HA!==void 0&&`adoptedStyleSheets`in e){e.adoptedStyleSheets.includes(HA)||(e.adoptedStyleSheets=[...e.adoptedStyleSheets,HA]);return}if(e.querySelector(`style[data-mathjax-chtml]`)!==null)return;let t=document.createElement(`style`);t.setAttribute(`data-mathjax-chtml`,``),t.textContent=VA,e.append(t)}function KA(){return BA!==void 0}function qA(){return UA().then(()=>void 0)}function JA(e,t){if(BA===void 0)throw new RA;return BA.convertLatex(e,t.displayMode)}var YA=new V.Renderer;YA.html=({text:e})=>Bk(e);var XA=1600,ZA=6e6,QA=8,$A=new Map,ej=0,tj=JA;function nj(e,t={}){let n=Uk(e),r=t.cache!==!1&&t.renderMath===void 0&&(!n||KA());if(r){let t=$A.get(e);if(t!==void 0)return $A.delete(e),$A.set(e,t),t.html}let i=aj(t.renderMath!==void 0||Uk(e)?Wk(e,t.renderMath??tj):V.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:YA}));return r&&rj(e,i),i}function rj(e,t){let n=e.length+t.length;if(n>ZA/QA)return;let r=$A.get(e);r!==void 0&&($A.delete(e),ej-=r.chars),$A.set(e,{html:t,chars:n}),ej+=n,ij()}function ij(){for(;$A.size>1&&($A.size>XA||ej>ZA);){let e=$A.entries().next();if(e.done===!0)break;let[t,n]=e.value;$A.delete(t),ej-=n.chars}}function aj(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`)&&!oj(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 oj(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}function sj({text:e,live:t}){return t&&(e.length>=24e3||Hk(e))}var cj=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 sj(this)?g`<div class="formatted plain" dir="auto">${this.text}</div>`:g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${jk(this.renderMarkdown())}</div>`}renderMarkdown(){return this.retryMathRender?(this.retryMathRender=!1,nj(this.text,{cache:!1,renderMath:JA})):nj(this.text,{cache:!this.live})}scheduleMathRetry(){this.mathRetryScheduled||KA()||this.live||!Hk(this.text)||(this.mathRetryScheduled=!0,qA().then(()=>{this.retryMathRender=!0,this.requestUpdate()}).catch(()=>{}))}updated(){this.enhanceCodeBlocks(),Hk(this.text)&&this.renderRoot instanceof ShadowRoot&&GA(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 FO(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=[xS,h`
2868
2868
  .formatted.plain { white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
2869
2869
  .math-inline { display: inline-block; max-width: 100%; overflow-x: auto; vertical-align: -0.25em; }
2870
2870
  .math-display { display: block; max-width: 100%; overflow-x: auto; margin: 10px 0; }
@@ -7470,7 +7470,7 @@ This will delete every archived session on this machine regardless of age or cle
7470
7470
  .git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
7471
7471
  .git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
7472
7472
  }
7473
- `}};H([x({attribute:!1})],nH.prototype,`onClose`,void 0),H([x({attribute:!1})],nH.prototype,`onStatusChange`,void 0),H([x({attribute:!1})],nH.prototype,`workspace`,void 0),H([x()],nH.prototype,`machineId`,void 0),H([x({attribute:!1})],nH.prototype,`api`,void 0),H([S()],nH.prototype,`status`,void 0),H([S()],nH.prototype,`selectedChange`,void 0),H([S()],nH.prototype,`selectedDiff`,void 0),H([S()],nH.prototype,`loadingStatus`,void 0),H([S()],nH.prototype,`loadingDiff`,void 0),H([S()],nH.prototype,`error`,void 0),H([S()],nH.prototype,`bounds`,void 0),nH=H([b(`git-update-manager-panel`)],nH);function rH(){kS(()=>import(`./UnifiedDiffViewer-CM42T5Lo.js`),[],import.meta.url)}function iH(e,t){let n=af(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function aH(e){return e===`staged`?`Staged`:`Unstaged`}function oH(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function sH(e){return e instanceof Error?e.message:String(e)}var cH=900*1e3,lH=750,uH=[1e3,3e3,8e3,15e3,3e4],dH={capture:!0},fH=`auto:on`,pH=`auto:off`,mH=`theme:`,hH=Ad(`core:workspace.files`),gH=Ad(`core:workspace.git`),_H=Ad(`core:workspace.terminal`),vH=`workspace-memory`,yH=`workspace.memory`,bH=`workspace-memory:workspace.memory`,xH=`workspace-learned-skills`,SH=`workspace.learned-skills`,CH=`workspace-learned-skills:workspace.learned-skills`,wH=`workspace-tasks`,TH=`workspace.tasks`,EH=320,DH=2,OH=`(min-width: 1181px)`,kH=75,AH=`Could not remember this model policy for future sessions.`,$=class extends y{constructor(e={}){super(),this.state=_d(),this.sessionUnread=new gx({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 Zg(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.hostSpeech=new r_({onStateChange:()=>{this.hostSpeechSurfaceVisible()&&this.requestUpdate()}}),this.sessions=new Qh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Nh,{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 cy(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new oy,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new xf(()=>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 Mf(()=>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 _f(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e),this.recentProjects.load()}}),this.machines=new pf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Pf(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new Ud(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Yd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new nf(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new Qd(()=>this.state,e=>{this.setState(e)}),this.recentProjects=new Cf({machineId:()=>R(this.state),onChange:()=>{this.requestUpdate()},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.keyboard=new gb,this.realtime=new Zm,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Qy,this.terminalSelection=new db,this.appShell=new aw(this),this.browserResume=new cw({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 Aw(this),this.panelResize=new Pw(this),this.navigationSections=new Dw(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=jH(),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=Rx()??Px,this.activeThemeId=Nx,this.isRefreshingApp=!1,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogGeneration=0,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new Hb({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 qb({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=TT(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=NT(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=JV()??[...HV],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=tT(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=eu(void 0),this.sessionWarningVisibility=wx(),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=vT(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. ${lU(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,YV(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`?gT(t.bounds,n,r):_T(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=CT(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=wT(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=kx(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 mw(e)),this.workspaceTasks=(e.createWorkspaceTasksController??(e=>new Cy(e)))({selectedScope:()=>XH(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=PH(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=Ex(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=NH(e,t);await this.updateComplete,!(!this.unreadConnected||PH(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);rU(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=zT(this.state.selectedProject?.name);this.windowTitleCleanup=BT(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=NH(e,t);return PH(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=ry({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(FH(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,dH),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},cH),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,dH),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(!nU(this.state,e))return;let t=this.state,n={...t,...e},r=FH(t),i=FH(n);IH(r,i)?t.status?.isCompacting!==!0&&n.status?.isCompacting===!0?this.hostSpeech.stop():this.abandonHostSpeechIfSourceInvalid(n):this.hostSpeech.select(i);let a=LH(t),o=zH(t),s=RH(t);this.state=n,s!==RH(this.state)&&(this.starterModelPolicySelectionGeneration+=1),a!==LH(this.state)&&this.resetActiveModelPolicyDraft(),PH(t)!==PH(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),QH(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),$H(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let c=zH(this.state);c!==void 0&&c!==o&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=Xw();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=lH){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=>tU(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(Xw(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?oU():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===``?oU():{selectedFilePath:Md(hH,`file`),selectedDiffPath:Md(gH,`diff`),selectedTerminalId:Md(_H,`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){Zw(e,{replace:!0}),Nd(hH,`file`,void 0,{replace:!0}),Nd(gH,`diff`,void 0,{replace:!0}),Nd(_H,`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=cU(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>=uH.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await fU(),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(),Zw({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(eb(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(eb(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Zw(tb(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Nd(hH,`file`,e.selectedFilePath,{replace:!0}),Nd(gH,`diff`,e.selectedDiffPath,{replace:!0}),Nd(_H,`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)??$y(e.id);if(await this.restoreRouteFor(tb(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=sU(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=cT(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(_H,`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,nT(e)}closeSettings(){this.settingsSection=void 0,nT(void 0)}navigateSettings(e){this.settingsSection=e,nT(e)}restoreSettingsRoute(){this.settingsSection=tT()}handleWorkspaceChange(e,t){let n=ZH(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&&!WH(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. ${lU(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 Zm;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=>eU(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):aU(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=iU(e),r=iU(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`
7473
+ `}};H([x({attribute:!1})],nH.prototype,`onClose`,void 0),H([x({attribute:!1})],nH.prototype,`onStatusChange`,void 0),H([x({attribute:!1})],nH.prototype,`workspace`,void 0),H([x()],nH.prototype,`machineId`,void 0),H([x({attribute:!1})],nH.prototype,`api`,void 0),H([S()],nH.prototype,`status`,void 0),H([S()],nH.prototype,`selectedChange`,void 0),H([S()],nH.prototype,`selectedDiff`,void 0),H([S()],nH.prototype,`loadingStatus`,void 0),H([S()],nH.prototype,`loadingDiff`,void 0),H([S()],nH.prototype,`error`,void 0),H([S()],nH.prototype,`bounds`,void 0),nH=H([b(`git-update-manager-panel`)],nH);function rH(){kS(()=>import(`./UnifiedDiffViewer-BFBQjlJd.js`),[],import.meta.url)}function iH(e,t){let n=af(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function aH(e){return e===`staged`?`Staged`:`Unstaged`}function oH(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function sH(e){return e instanceof Error?e.message:String(e)}var cH=900*1e3,lH=750,uH=[1e3,3e3,8e3,15e3,3e4],dH={capture:!0},fH=`auto:on`,pH=`auto:off`,mH=`theme:`,hH=Ad(`core:workspace.files`),gH=Ad(`core:workspace.git`),_H=Ad(`core:workspace.terminal`),vH=`workspace-memory`,yH=`workspace.memory`,bH=`workspace-memory:workspace.memory`,xH=`workspace-learned-skills`,SH=`workspace.learned-skills`,CH=`workspace-learned-skills:workspace.learned-skills`,wH=`workspace-tasks`,TH=`workspace.tasks`,EH=320,DH=2,OH=`(min-width: 1181px)`,kH=75,AH=`Could not remember this model policy for future sessions.`,$=class extends y{constructor(e={}){super(),this.state=_d(),this.sessionUnread=new gx({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 Zg(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.hostSpeech=new r_({onStateChange:()=>{this.hostSpeechSurfaceVisible()&&this.requestUpdate()}}),this.sessions=new Qh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Nh,{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 cy(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new oy,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new xf(()=>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 Mf(()=>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 _f(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e),this.recentProjects.load()}}),this.machines=new pf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Pf(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new Ud(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Yd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new nf(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new Qd(()=>this.state,e=>{this.setState(e)}),this.recentProjects=new Cf({machineId:()=>R(this.state),onChange:()=>{this.requestUpdate()},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.keyboard=new gb,this.realtime=new Zm,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Qy,this.terminalSelection=new db,this.appShell=new aw(this),this.browserResume=new cw({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 Aw(this),this.panelResize=new Pw(this),this.navigationSections=new Dw(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=jH(),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=Rx()??Px,this.activeThemeId=Nx,this.isRefreshingApp=!1,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogGeneration=0,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new Hb({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 qb({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=TT(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=NT(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=JV()??[...HV],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=tT(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=eu(void 0),this.sessionWarningVisibility=wx(),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=vT(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. ${lU(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,YV(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`?gT(t.bounds,n,r):_T(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=CT(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=wT(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=kx(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 mw(e)),this.workspaceTasks=(e.createWorkspaceTasksController??(e=>new Cy(e)))({selectedScope:()=>XH(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=PH(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=Ex(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=NH(e,t);await this.updateComplete,!(!this.unreadConnected||PH(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);rU(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=zT(this.state.selectedProject?.name);this.windowTitleCleanup=BT(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=NH(e,t);return PH(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=ry({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(FH(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,dH),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},cH),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,dH),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(!nU(this.state,e))return;let t=this.state,n={...t,...e},r=FH(t),i=FH(n);IH(r,i)?t.status?.isCompacting!==!0&&n.status?.isCompacting===!0?this.hostSpeech.stop():this.abandonHostSpeechIfSourceInvalid(n):this.hostSpeech.select(i);let a=LH(t),o=zH(t),s=RH(t);this.state=n,s!==RH(this.state)&&(this.starterModelPolicySelectionGeneration+=1),a!==LH(this.state)&&this.resetActiveModelPolicyDraft(),PH(t)!==PH(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),QH(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),$H(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let c=zH(this.state);c!==void 0&&c!==o&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=Xw();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=lH){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=>tU(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(Xw(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?oU():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===``?oU():{selectedFilePath:Md(hH,`file`),selectedDiffPath:Md(gH,`diff`),selectedTerminalId:Md(_H,`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){Zw(e,{replace:!0}),Nd(hH,`file`,void 0,{replace:!0}),Nd(gH,`diff`,void 0,{replace:!0}),Nd(_H,`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=cU(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>=uH.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await fU(),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(),Zw({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(eb(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(eb(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Zw(tb(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Nd(hH,`file`,e.selectedFilePath,{replace:!0}),Nd(gH,`diff`,e.selectedDiffPath,{replace:!0}),Nd(_H,`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)??$y(e.id);if(await this.restoreRouteFor(tb(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=sU(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=cT(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(_H,`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,nT(e)}closeSettings(){this.settingsSection=void 0,nT(void 0)}navigateSettings(e){this.settingsSection=e,nT(e)}restoreSettingsRoute(){this.settingsSection=tT()}handleWorkspaceChange(e,t){let n=ZH(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&&!WH(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. ${lU(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 Zm;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=>eU(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):aU(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=iU(e),r=iU(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`
7474
7474
  <workspace-panel
7475
7475
  id="workspace-panel"
7476
7476
  .emptyState=${this.state.selectedWorkspace===void 0?this.workspacePanelEmptyState():void 0}