@hyperdreamer/pi-webui 1.11.5 → 1.11.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{CodeViewer-4JowHC78.js → CodeViewer-DUqxkZ3h.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-C99T12hF.js → UnifiedDiffViewer-CqMCpp0S.js} +1 -1
- package/dist/client/assets/{index-uzrr_ofX.js → index-BjHB0gQv.js} +246 -244
- package/dist/client/index.html +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-DUqxkZ3h.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j as u,l as d,p as f,q as p,u as m}from"./vendor-editor-core-vUi74DnD.js";import{a as ee,o as te,s as ne}from"./vendor-editor-languages-DoaXUodB.js";import{n as re,t as ie}from"./vendor-terminal-D8k4UKM2.js";var ae=Object.defineProperty,oe=(e,t)=>{let n={};for(var r in e)ae(n,r,{get:e[r],enumerable:!0});return t||ae(n,Symbol.toStringTag,{value:`Module`}),n};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var se=globalThis,ce=se.ShadowRoot&&(se.ShadyCSS===void 0||se.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,le=Symbol(),ue=new WeakMap,de=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==le)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(ce&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=ue.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&ue.set(t,e))}return e}toString(){return this.cssText}},fe=e=>new de(typeof e==`string`?e:e+``,void 0,le),h=(e,...t)=>new de(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,le),pe=(e,t)=>{if(ce)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=se.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},me=ce?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return fe(t)})(e):e,{is:he,defineProperty:ge,getOwnPropertyDescriptor:_e,getOwnPropertyNames:ve,getOwnPropertySymbols:ye,getPrototypeOf:be}=Object,xe=globalThis,Se=xe.trustedTypes,Ce=Se?Se.emptyScript:``,we=xe.reactiveElementPolyfillSupport,Te=(e,t)=>e,Ee={toAttribute(e,t){switch(t){case Boolean:e=e?Ce:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},De=(e,t)=>!he(e,t),Oe={attribute:!0,type:String,converter:Ee,reflect:!1,useDefault:!1,hasChanged:De};Symbol.metadata??=Symbol(`metadata`),xe.litPropertyMetadata??=new WeakMap;var ke=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Oe){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&ge(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=_e(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Oe}static _$Ei(){if(this.hasOwnProperty(Te(`elementProperties`)))return;let e=be(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Te(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Te(`properties`))){let e=this.properties,t=[...ve(e),...ye(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(me(e))}else e!==void 0&&t.push(me(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return pe(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?Ee:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?Ee:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??De)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};ke.elementStyles=[],ke.shadowRootOptions={mode:`open`},ke[Te(`elementProperties`)]=new Map,ke[Te(`finalized`)]=new Map,we?.({ReactiveElement:ke}),(xe.reactiveElementVersions??=[]).push(`2.1.2`);var Ae=globalThis,je=e=>e,Me=Ae.trustedTypes,Ne=Me?Me.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Pe=`$lit$`,Fe=`lit$${Math.random().toFixed(9).slice(2)}$`,Ie=`?`+Fe,Le=`<${Ie}>`,Re=document,ze=()=>Re.createComment(``),Be=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Ve=Array.isArray,He=e=>Ve(e)||typeof e?.[Symbol.iterator]==`function`,Ue=`[
|
|
3
3
|
\f\r]`,We=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ge=/-->/g,Ke=/>/g,qe=RegExp(`>|${Ue}(?:([^\\s"'>=/]+)(${Ue}*=${Ue}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Je=/'/g,Ye=/"/g,Xe=/^(?:script|style|textarea|title)$/i,Ze=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=Ze(1),_=Ze(2),Qe=Symbol.for(`lit-noChange`),v=Symbol.for(`lit-nothing`),$e=new WeakMap,et=Re.createTreeWalker(Re,129);function tt(e,t){if(!Ve(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ne===void 0?t:Ne.createHTML(t)}var nt=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=We;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===We?c[1]===`!--`?o=Ge:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=qe):(Xe.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=qe):o=Ke:o===qe?c[0]===`>`?(o=i??We,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?qe:c[3]===`"`?Ye:Je):o===Ye||o===Je?o=qe:o===Ge||o===Ke?o=We:(o=qe,i=void 0);let d=o===qe&&e[t+1].startsWith(`/>`)?` `:``;a+=o===We?n+Le:l>=0?(r.push(s),n.slice(0,l)+Pe+n.slice(l)+Fe+d):n+Fe+(l===-2?t:d)}return[tt(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},rt=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=nt(t,n);if(this.el=e.createElement(l,r),et.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=et.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Pe)){let t=u[o++],n=i.getAttribute(e).split(Fe),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ct:r[1]===`?`?lt:r[1]===`@`?ut:st}),i.removeAttribute(e)}else e.startsWith(Fe)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Xe.test(i.tagName)){let e=i.textContent.split(Fe),t=e.length-1;if(t>0){i.textContent=Me?Me.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],ze()),et.nextNode(),c.push({type:2,index:++a});i.append(e[t],ze())}}}else if(i.nodeType===8)if(i.data===Ie)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Fe,e+1))!==-1;)c.push({type:7,index:a}),e+=Fe.length-1}a++}}static createElement(e,t){let n=Re.createElement(`template`);return n.innerHTML=e,n}};function it(e,t,n=e,r){if(t===Qe)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Be(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=it(e,i._$AS(e,t.values),i,r)),t}var at=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??Re).importNode(t,!0);et.currentNode=r;let i=et.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new ot(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new dt(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=et.nextNode(),a++)}return et.currentNode=Re,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},ot=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=v,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=it(this,e,t),Be(e)?e===v||e==null||e===``?(this._$AH!==v&&this._$AR(),this._$AH=v):e!==this._$AH&&e!==Qe&&this._(e):e._$litType$===void 0?e.nodeType===void 0?He(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==v&&Be(this._$AH)?this._$AA.nextSibling.data=e:this.T(Re.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=rt.createElement(tt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new at(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=$e.get(e.strings);return t===void 0&&$e.set(e.strings,t=new rt(e)),t}k(t){Ve(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(ze()),this.O(ze()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=je(e).nextSibling;je(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},st=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=v,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=v}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=it(this,e,t,0),a=!Be(e)||e!==this._$AH&&e!==Qe,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=it(this,r[n+o],t,o),s===Qe&&(s=this._$AH[o]),a||=!Be(s)||s!==this._$AH[o],s===v?e=v:e!==v&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===v?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},ct=class extends st{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===v?void 0:e}},lt=class extends st{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==v)}},ut=class extends st{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=it(this,e,t,0)??v)===Qe)return;let n=this._$AH,r=e===v&&n!==v||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==v&&(n===v||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},dt=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){it(this,e)}},ft={M:Pe,P:Fe,A:Ie,C:1,L:nt,R:at,D:He,V:it,I:ot,H:st,N:lt,U:ut,B:ct,F:dt},pt=Ae.litHtmlPolyfillSupport;pt?.(rt,ot),(Ae.litHtmlVersions??=[]).push(`3.3.3`);var mt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new ot(t.insertBefore(ze(),e),e,void 0,n??{})}return i._$AI(e),i},ht=globalThis,y=class extends ke{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=mt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Qe}};y._$litElement$=!0,y.finalized=!0,ht.litElementHydrateSupport?.({LitElement:y});var gt=ht.litElementPolyfillSupport;gt?.({LitElement:y}),(ht.litElementVersions??=[]).push(`4.2.2`);var b=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},_t={attribute:!0,type:String,converter:Ee,reflect:!1,hasChanged:De},vt=(e=_t,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function x(e){return(t,n)=>typeof n==`object`?vt(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function S(e){return x({...e,state:!0,attribute:!1})}var yt=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function C(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return yt(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return yt(n,r,{get(){return a(this)}})}}var w={sessionsDeleteArchived:`sessions.deleteArchived`,sessionsBulkMutations:`sessions.bulkMutations`,sessionsCleanup:`sessions.cleanup`,sessionsReload:`sessions.reload`,sessionsClearQueue:`sessions.clearQueue`,sessionsMessageActions:`sessions.messageActions`,sessionsSystemPrompt:`sessions.systemPrompt`,sessionsPersistedState:`sessions.persistedState`,sessionsNotifications:`sessions.notifications`,sessionsUnread:`sessions.unread`,promptAttachments:`prompt.attachments`,workspaceFileSuggestions:`workspace.fileSuggestions`,piPackagesManage:`piPackages.manage`,selectedMachineSettings:`settings.selectedMachine`,agentProfileConfig:`settings.agentProfile`,modelTierSettings:`settings.modelTiers`,utilityModelSettings:`settings.utilityModels`,sessionsModelPolicy:`sessions.modelPolicy`,sessionsModelPolicyDefaults:`sessions.modelPolicyDefaults`,sessionsModelPolicyStarterSelection:`sessions.modelPolicyStarterSelection`,sessionsReorder:`sessions.reorder`,projectUsageStatistics:`project.usageStatistics`},bt=[`economy`,`fast`,`standard`,`advanced`,`capable`,`frontier`],xt=[`lightweight`,`context`],St=1e3,Ct=1e3,wt=32*1024,Tt=8*1024,Et=1e4;function Dt(e,t=kt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(At(e),n).toString()}function Ot(e,t=kt()){let n=new URL(Dt(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 kt(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function At(e){return e.startsWith(`/`)?`.${e}`:e}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(Dt(e),{...n,headers:r});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(jt(e)??i.statusText)}return t(await i.json())}function jt(e){if(Mt(e))return typeof e.error==`string`?e.error:void 0}function Mt(e){return typeof e==`object`&&!!e}function Nt(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function Pt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&Nt(e)}var Ft=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),It=/^sha256:[0-9a-f]{64}$/u,Lt=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,Rt=new Set([`PI_WEBUI_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function zt(e){if(!Wt(e)||Object.keys(e).some(e=>!Ft.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`||!It.test(n))&&!(typeof r!=`string`||!Bt(r))&&!(typeof i!=`string`||!Vt(i))&&Ut(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEBUI_AGENT_SESSION_DIR`||a.some(e=>!Rt.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Bt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:Vt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):Lt.test(e)}function Vt(e){if(e===``||e!==e.trim()||Ht(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Ht(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Ut(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Wt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Gt=Object.values(w),Kt=new Set(Gt);w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,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.sessionsReorder,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsReorder,w.projectUsageStatistics,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,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.sessionsReorder,w.projectUsageStatistics;function qt(e){return typeof e==`string`&&Kt.has(e)}function E(e,t){return e?.capabilities?.includes(t)===!0}function Jt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(qt)}var Yt=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Xt(e){return Yt.some(t=>t===e)}function Zt(e){return e===void 0||e===``?`off`:e}function Qt(e,t){let n=t.length>=2?t:Yt,r=n.length-1,i=Zt(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}function $t(e){return typeof e==`object`&&!!e}function D(e){if(!$t(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 en(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function tn(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function nn(e){if(!$t(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:rn(e.globalEntries),projectEntries:rn(e.projectEntries),...typeof e.projectUnavailableMessage==`string`?{projectUnavailableMessage:e.projectUnavailableMessage}:{}}}function rn(e){if(!Array.isArray(e))throw Error(`Invalid memory snapshot response`);return e.map(e=>{if(!$t(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 an(e){if(!$t(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:on(e.globalSkills),projectSkills:on(e.projectSkills),...t===void 0?{}:{projectUnavailableMessage:t}}}function on(e){if(!Array.isArray(e))throw Error(`Invalid learned skills snapshot response`);return e.map(sn)}function sn(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 cn(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=D(e);return{messages:en(t.messages),start:A(t,`start`),total:A(t,`total`)}}function ln(e){let t=D(e);return M(un)(t.machines)}function un(e){let t=D(e),n=pn(t,`kind`),r=k(t,`baseUrl`),i=mn(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 dn(e){let t=D(e),n=mn(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:Ia(t.web)},...t.sessiond===void 0?{}:{sessiond:Ia(t.sessiond)},...r===void 0?{}:{error:r}}}function fn(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:Pa(t.components)},...t.capabilities===void 0?{}:{capabilities:Ha(t.capabilities)},...n===void 0?{}:{error:n}}}function pn(e,t){let n=O(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function mn(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 hn(e){let t=D(e),n=Aa(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 gn(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`,_n(t.effectiveConfig))}}function _n(e){if(e!==void 0){if(!$t(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...P(`uploads`,sa(e.uploads))}}}function vn(e){let t=D(e),n=k(t,`name`),r=Aa(t.persisted,`persisted`),i=k(t,`parentSessionPath`),a=k(t,`archivedAt`),o=Aa(t.pinned,`pinned`),s=t.creationSource===`session-list-plus`?t.creationSource:void 0,c=t.manualOrder===void 0?void 0:or(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 yn(e){let t=D(e);return{id:O(t,`id`),cwd:O(t,`cwd`),manualOrder:or(t,`manualOrder`)}}function bn(e){let t=D(e);return{orderedSessions:M(yn)(t.orderedSessions)}}function xn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function Sn(e){if(e!==void 0)return{id:O(D(e),`id`)}}function Cn(e){let t=D(e),n=Sn(t.dismiss);return{severity:xn(t.severity),message:O(t,`message`),...P(`source`,k(t,`source`)),...P(`path`,k(t,`path`)),...n===void 0?{}:{dismiss:n}}}function wn(e){return e===void 0?{}:{warnings:M(Cn)(e)}}function Tn(e){let t=D(e);return{sessionId:O(t,`sessionId`),...P(`persisted`,Aa(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(yr)(t.queuedMessages),...P(`messageCount`,N(t,`messageCount`)),tokens:br(t.tokens),cost:A(t,`cost`),...di(t.generation),...Sr(t.model),...P(`modelPolicy`,t.modelPolicy===void 0?void 0:jn(t.modelPolicy)),...fi(t.contextUsage),...P(`thinkingLevel`,k(t,`thinkingLevel`)),...wn(t.warnings)}}function En(e){let t=In(e,`session model policy response`);if(Rn(t,[`contractVersion`,`policy`,`session`],`session model policy response`),t.contractVersion!==1)throw Error(`Invalid session model policy contract version`);let n=Tn(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:Dn(t.policy),session:n}}function Dn(e){let t=In(e,`session model policy`);Rn(t,[`mode`,`exact`,`tier`],`session model policy`);let n=Pn(t.mode),r=Fn(t,`session model policy`);if(n===`tiered`&&r===void 0)throw Error(`Tiered session model policy requires a tier`);return{mode:n,exact:Mn(t.exact),...P(`tier`,r)}}function On(e){let t=In(e,`starter model policy preference`);Rn(t,[`mode`,`tier`],`starter model policy preference`);let n=Pn(t.mode),r=Fn(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 kn(e){let t=In(e,`starter model policy preference`);return Object.hasOwn(t,`exact`)?An(t):On(t)}function An(e){let t=In(e,`confirmed starter model policy preference`);Rn(t,[`mode`,`exact`,`tier`],`confirmed starter model policy preference`);let n=Pn(t.mode),r=Fn(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:Mn(t.exact),...P(`tier`,r)}}function jn(e){let t=In(e,`session model policy status`);Rn(t,[`mode`,`tier`,`resolved`,`ladderValid`,`blockedReason`],`session model policy status`);let n=Pn(t.mode),r=Fn(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:Mn(t.resolved),ladderValid:j(t,`ladderValid`),...P(`blockedReason`,k(t,`blockedReason`))}}function Mn(e){let t=In(e,`exact selection`);return Rn(t,[`model`,`thinkingLevel`],`exact selection`),{model:Nn(t.model),thinkingLevel:Qa(t,`thinkingLevel`)}}function Nn(e){let t=In(e,`model reference`);return Rn(t,[`provider`,`id`],`model reference`),{provider:Qa(t,`provider`),id:Qa(t,`id`)}}function Pn(e){if(e!==`exact`&&e!==`tiered`)throw Error(`Invalid session model policy mode`);return e}function Fn(e,t){if(!Object.hasOwn(e,`tier`))return;let n=e.tier;if(typeof n!=`string`||!Qi(n))throw Error(`Invalid ${t} tier`);return n}function In(e,t){if(!Ln(e))throw Error(`Expected ${t} object`);return e}function Ln(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Reflect.getPrototypeOf(e);return t===Object.prototype||t===null}function Rn(e,t,n){let r=Object.keys(e).find(e=>!t.includes(e));if(r!==void 0)throw Error(`Invalid ${n} field: ${r}`)}function zn(e){let t=D(e);return{seq:A(t,`seq`),partial:t.partial??null}}function Bn(e){let t=k(D(e),`systemPrompt`);return t===void 0?{}:{systemPrompt:t}}function Vn(e){let t=D(e),n=or(t,`catalogRevision`),r=rr(t.sessions,Un,Ct,`sessions`);if(Wn(r),Gn(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:Kn(t,`catalogId`,512),catalogRevision:n,sessions:r}}function Hn(e){let t=D(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=Kn(t,`sessionId`,512),r=Kn(t,`cwd`,wt),i=qn(t,`catalogRevision`),a=t.unread===null?null:Un(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:Kn(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Un(e){let t=D(e),n=Kn(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:Kn(t,`sessionId`,512),cwd:Kn(t,`cwd`,wt),completionOrder:qn(t,`completionOrder`),completedAt:n}}function Wn(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 Gn(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 Kn(e,t,n){let r=ar(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function qn(e,t){let n=or(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function Jn(e){let t=D(e),n=Xn(t.summary),r=rr(t.notifications,Zn,100,`notifications`);if(sr(r),cr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==ur(r))throw Error(`Notification snapshot severity mismatch`);let i=Qn(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:ar(t,`daemonInstanceId`),catalogRevision:or(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Yn(e){let t=D(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=Xn(t.summary),r=Qn(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=$n(t.delta);if(i.kind===`cleared`&&!lr(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:ar(t,`daemonInstanceId`),catalogRevision:or(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function Xn(e){let t=D(e),n=or(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=or(t,`discardedCount`),i=tr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:ar(t,`sessionId`),cwd:ar(t,`cwd`),inboxRevision:or(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Zn(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=or(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:ar(t,`id`),message:n,truncated:j(t,`truncated`),severity:er(t.severity),receivedAt:r,order:i}}function Qn(e){let t=D(e);return{order:or(t,`order`),overflowWatermark:or(t,`overflowWatermark`)}}function $n(e){let t=D(e);switch(t.kind){case`added`:{let e=k(t,`evictedNotificationId`);return{kind:`added`,notification:Zn(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=rr(t.notificationIds,ir,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:nr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function er(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function tr(e){return e===void 0?void 0:er(e)}function nr(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 rr(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 ir(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function ar(e,t){let n=O(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function or(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 sr(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 cr(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 lr(e){return e.retainedCount===0&&e.discardedCount===0}function ur(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function dr(e){let t=D(e),n=t.skippedBusySessionIds===void 0?void 0:tn(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:O(t,`generatedAt`),thresholds:gr(t.thresholds),projects:M(_r)(t.projects),totals:vr(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function fr(e){let t=D(e);return{...dr(t),archivedSessionIds:tn(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:tn(t.deletedSessionIds,`deletedSessionIds`)}}function pr(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:tn(t.archivedSessionIds,`archivedSessionIds`),failures:M(hr)(t.failures),generatedAt:O(t,`generatedAt`)}}function mr(e){let t=D(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:tn(t.deletedSessionIds,`deletedSessionIds`),failures:M(hr)(t.failures),generatedAt:O(t,`generatedAt`)}}function hr(e){let t=D(e);return{sessionId:O(t,`sessionId`),error:O(t,`error`)}}function gr(e){let t=D(e);return{...P(`archiveIdleDays`,N(t,`archiveIdleDays`)),...P(`deleteArchivedDays`,N(t,`deleteArchivedDays`))}}function _r(e){let t=D(e);return{cwd:O(t,`cwd`),archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function vr(e){let t=D(e);return{archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function yr(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 br(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 xr(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 Sr(e){return e===void 0?{}:{model:xr(e)}}function Cr(e){let t=D(e);return{models:M(xr)(t.models)}}function wr(e){let t=D(e),n=t.starterModelPolicyPreference===void 0?void 0:On(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:xr(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(xr)(t.models),thinkingLevels:tn(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function Tr(e){let t=In(e,`version-two session defaults response`);if(Rn(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:kn(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:xr(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(xr)(t.models),thinkingLevels:tn(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function Er(e){let t=kr(e,`models configuration`),n=t.providers;if(n===void 0)return{...t,providers:{}};let r=kr(n,`models configuration providers`),i={};for(let[e,t]of Object.entries(r))i[e]=Dr(t);return{...t,providers:i}}function Dr(e){let t=kr(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=Ar(t.headers,`models configuration provider headers`);o!==void 0&&(n.headers=jr(o,`models configuration provider headers`));let s=Ar(t.compat,`models configuration provider compatibility`);s!==void 0&&(n.compat={...s});let c=Ar(t.modelOverrides,`models configuration provider model overrides`);c!==void 0&&(n.modelOverrides={...c});let l=t.models;if(l!==void 0){if(!Array.isArray(l))throw Error(`Expected models configuration models array`);n.models=l.map(Or)}return n}function Or(e){let t=kr(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=go(t,`reasoning`);a!==void 0&&(n.reasoning=a);let o=Ar(t.thinkingLevelMap,`models configuration thinking level map`);o!==void 0&&(n.thinkingLevelMap=Mr(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=Ar(t.cost,`models configuration model cost`);u!==void 0&&(n.cost=Nr(u));let d=Ar(t.compat,`models configuration model compatibility`);return d!==void 0&&(n.compat={...d}),n}function kr(e,t){if(!$t(e)||Array.isArray(e))throw Error(`Expected ${t} object`);return e}function Ar(e,t){if(e!==void 0)return kr(e,t)}function jr(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 Mr(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 Nr(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 Pr(e){if(D(e).success!==!0)throw Error(`Expected successful models configuration save`);return{success:!0}}function Fr(e){let t=D(e);return{models:M(Ir)(t.models)}}function Ir(e){let t=D(e),n=O(t,`id`),r=k(t,`name`);return r===void 0?{id:n}:{id:n,name:r}}function Lr(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 Rr(e){let t=D(e);return{skills:M(zr)(t.skills)}}function zr(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:Br(t.install)}}}function Br(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:Vr(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 Vr(e){if(e!==`global`&&e!==`project`)throw Error(`Expected skill install scope`);return e}function Hr(e){if(D(e).success!==!0)throw Error(`Expected successful Skills mutation`);return{success:!0}}function Ur(e){let t=D(e);return{results:M(Wr)(t.results)}}function Wr(e){let t=D(e);return{package:O(t,`package`),installs:O(t,`installs`),url:O(t,`url`)}}function Gr(e){let t=D(e);return{updates:M(Kr)(t.updates)}}function Kr(e){let t=D(e),n=k(t,`currentVersion`),r=k(t,`latestVersion`),i=k(t,`message`);return{package:O(t,`package`),scope:Vr(t.scope),state:qr(t.state),...n===void 0?{}:{currentVersion:n},...r===void 0?{}:{latestVersion:r},...i===void 0?{}:{message:i}}}function qr(e){if(e!==`up-to-date`&&e!==`update-available`&&e!==`unsupported`&&e!==`error`)throw Error(`Expected skill update state`);return e}function Jr(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:zr(t.skill)},...n===void 0?{}:{output:n}}}function Yr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Xr(e){let t=D(e);return{levels:M(Yr)(t.levels)}}function Zr(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Qr(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 $r(e){let t=D(e),n=t.source===void 0?void 0:Qr(t.source);return{configured:j(t,`configured`),...P(`source`,n),...P(`label`,k(t,`label`))}}function ei(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:Zr(t.authType),status:$r(t.status),...n===void 0?{}:{loginFlow:n}}}function ti(e){let t=D(e);return{providers:M(ei)(t.providers)}}function ni(e){let t=D(e);return{flowId:O(t,`flowId`),providerId:O(t,`providerId`),providerName:O(t,`providerName`),status:ri(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`,ii(t.auth)),...P(`prompt`,oi(t.prompt)),...P(`select`,ci(t.select)),...P(`info`,li(t.info))}}function ri(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function ii(e){if(e===void 0)return;let t=D(e);return{url:O(t,`url`),...P(`instructions`,k(t,`instructions`)),...P(`deviceCode`,ai(t.deviceCode))}}function ai(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 oi(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`:si(t.promptType);return{requestId:O(t,`requestId`),message:O(t,`message`),kind:n,promptType:r,...P(`placeholder`,k(t,`placeholder`)),...P(`allowEmpty`,go(t,`allowEmpty`))}}function si(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function ci(e){if(e===void 0)return;let t=D(e);return{requestId:O(t,`requestId`),message:O(t,`message`),options:M(eo)(t.options)}}function li(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(ui)(t.links))}})(e)}function ui(e){let t=D(e);return{url:O(t,`url`),...P(`label`,k(t,`label`))}}function di(e){if(e===void 0)return{};let t=D(e);return{generation:{outputTokens:A(t,`outputTokens`),...P(`tokensPerSecond`,N(t,`tokensPerSecond`)),...P(`estimated`,go(t,`estimated`))}}}function fi(e){if(e===void 0)return{};let t=D(e);return{contextUsage:{tokens:_o(t,`tokens`),contextWindow:A(t,`contextWindow`),percent:_o(t,`percent`)}}}function pi(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 mi(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 hi(e){let t=D(e);return{path:O(t,`path`),entries:M(gi)(t.entries),scannedAt:O(t,`scannedAt`),truncated:j(t,`truncated`)}}function gi(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 _i(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`,xi(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 vi(e){let t=D(e);return{path:O(t,`path`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`),created:j(t,`created`)}}function yi(e){let t=D(e);return{path:O(t,`path`),existed:j(t,`existed`)}}function bi(e){let t=D(e);return{fromPath:O(t,`fromPath`),toPath:O(t,`toPath`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`)}}function xi(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function Si(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(Ci)(t.files)}}function Ci(e){let t=D(e);return{path:O(t,`path`),...P(`oldPath`,k(t,`oldPath`)),index:wi(t.index),workingTree:wi(t.workingTree)}}function wi(e){switch(e){case`unmodified`:case`modified`:case`added`:case`deleted`:case`renamed`:case`copied`:case`untracked`:case`ignored`:case`conflicted`:return e;default:throw Error(`Invalid git file state`)}}function Ti(e){let t=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 Ei(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 Di(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:Oi(t.status),...P(`exitCode`,N(t,`exitCode`)),createdAt:O(t,`createdAt`),...P(`startedAt`,k(t,`startedAt`)),...P(`completedAt`,k(t,`completedAt`)),metadata:ki(t.metadata,`metadata`)}}function Oi(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function ki(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 Ai(e){let t=D(e);return{cwd:O(t,`cwd`),hasSessionActivity:j(t,`hasSessionActivity`),hasTerminalActivity:j(t,`hasTerminalActivity`),updatedAt:O(t,`updatedAt`)}}function ji(e){let t=D(e);return{workspaces:M(Ai)(t.workspaces),generatedAt:O(t,`generatedAt`)}}function Mi(e){let t=ea(e,`utility model settings response`),n=Object.keys(t).find(e=>!Fi(e));if(n!==void 0)throw Error(`Invalid utility model settings response field: ${n}`);if(t.contractVersion===1)return Ni(t);if(t.contractVersion===2)return Pi(t);throw Error(`Invalid utility model settings contract version`)}function Ni(e){let t=k(e,`configError`);return{contractVersion:1,settings:Ii(e.settings),models:M(zi)(e.models),slots:Vi(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function Pi(e){let t=k(e,`configError`);return{contractVersion:2,settings:Li(e.settings),models:M(Bi)(e.models),slots:Vi(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function Fi(e){return e===`contractVersion`||e===`settings`||e===`models`||e===`slots`||e===`valid`||e===`configError`}function Ii(e){let t=ea(e,`settings`),n=Object.keys(t).find(e=>!Ui(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:Ji(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:Ji(t.context,`settings.context`))}}function Li(e){let t=ea(e,`settings`),n=Object.keys(t).find(e=>!Ui(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:Ri(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:Ri(t.context,`settings.context`))}}function Ri(e,t){let n=ea(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=ar(n,`provider`),a=ar(n,`id`),o=k(n,`thinkingLevel`);if(o===void 0)return{provider:i,id:a};if(!Xt(o))throw Error(`Invalid utility model thinking level: ${t}.thinkingLevel`);return{provider:i,id:a,thinkingLevel:o}}function zi(e){let t=ea(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:Ji(t.model,`models.model`),...P(`name`,k(t,`name`))}}function Bi(e){let t=ea(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=tn(t.thinkingLevels,`models.thinkingLevels`).map(e=>{if(!Xt(e))throw Error(`Invalid utility model thinking levels: models.thinkingLevels`);return e});return{model:Ji(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:r}}function Vi(e){let t=Wi(e,`slots`);return{lightweight:Hi(t.lightweight,`slots.lightweight`),context:Hi(t.context,`slots.context`)}}function Hi(e,t){let n=ea(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 Ui(e){return xt.some(t=>t===e)}function Wi(e,t){let n=ea(e,t),r=Object.keys(n).find(e=>!Ui(e));if(r!==void 0)throw Error(`Invalid utility model ${t} field: unknown slot ${r}`);let i=xt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid utility model ${t} field: missing slot ${i}`);return n}function Gi(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:Ki(t.ladder),r=k(t,`configError`);return{contractVersion:1,...P(`ladder`,n),models:M(Yi)(t.models),rows:Xi(t.rows),valid:j(t,`valid`),...P(`configError`,r)}}function Ki(e){let t=$i(e,`ladder`);return{economy:qi(t.economy,`ladder.economy`),fast:qi(t.fast,`ladder.fast`),standard:qi(t.standard,`ladder.standard`),advanced:qi(t.advanced,`ladder.advanced`),capable:qi(t.capable,`ladder.capable`),frontier:qi(t.frontier,`ladder.frontier`)}}function qi(e,t){let n=ea(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:Ji(n.model,`${t}.model`),thinkingLevel:ar(n,`thinkingLevel`)}}function Ji(e,t){let n=ea(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:ar(n,`provider`),id:ar(n,`id`)}}function Yi(e){let t=ea(e,`models`);return{model:Ji(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:tn(t.thinkingLevels,`models.thinkingLevels`)}}function Xi(e){let t=$i(e,`rows`);return{economy:Zi(t.economy,`rows.economy`),fast:Zi(t.fast,`rows.fast`),standard:Zi(t.standard,`rows.standard`),advanced:Zi(t.advanced,`rows.advanced`),capable:Zi(t.capable,`rows.capable`),frontier:Zi(t.frontier,`rows.frontier`)}}function Zi(e,t){let n=ea(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 Qi(e){return bt.some(t=>t===e)}function $i(e,t){let n=ea(e,t),r=Object.keys(n).find(e=>!Qi(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 ea(e,t){if(!$t(e)||Array.isArray(e))throw Error(`Expected object field: ${t}`);return e}function ta(e){let t=D(e);return{path:O(t,`path`),exists:j(t,`exists`),config:na(t.config),effectiveConfig:na(t.effectiveConfig),envOverrides:fa(t.envOverrides)}}function na(e){let t=D(e);return{...P(`host`,k(t,`host`)),...P(`port`,N(t,`port`)),...P(`allowedHosts`,ia(t.allowedHosts)),...P(`shortcuts`,ua(t.shortcuts)),...P(`plugins`,da(t.plugins)),...P(`pathAccess`,aa(t.pathAccess)),...P(`uploads`,sa(t.uploads)),...P(`maxUploadBytes`,N(t,`maxUploadBytes`)),...P(`agent`,ra(t.agent)),...P(`spawnSessions`,go(t,`spawnSessions`)),...P(`subsessions`,go(t,`subsessions`))}}function ra(e){if(e!==void 0){if(!$t(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI agent field`);return{...P(`command`,k(e,`command`)),...P(`dir`,k(e,`dir`))}}}function ia(e){if(e!==void 0){if(e===!0)return!0;if(ca(e))return e;throw Error(`Invalid PI WEBUI allowedHosts field`)}}function aa(e){if(e===void 0)return;if(!$t(e))throw Error(`Invalid PI WEBUI pathAccess field`);let t=e.allowedPaths;return{...P(`allowedPaths`,oa(t,`pathAccess.allowedPaths`))}}function oa(e,t){if(e!==void 0){if(la(e))return e;throw Error(`Invalid PI WEBUI ${t} field`)}}function sa(e){if(e!==void 0){if(!$t(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI uploads field`);return{...P(`defaultFolder`,k(e,`defaultFolder`))}}}function ca(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function la(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function ua(e){if(e!==void 0){if(!$t(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 da(e){if(e!==void 0){if(!$t(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!$t(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&&(!$t(r)||Array.isArray(r)))throw Error(`Invalid PI WEBUI plugin settings field`);return[e,t]}))}}function fa(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:go(t,`agentCommand`)??!1,agentDir:go(t,`agentDir`)??!1,...pa(t),agentSessionDir:go(t,`agentSessionDir`)??!1}}function pa(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 ma(e){let t=D(e);return{packages:M(ga)(t.packages)}}function ha(e){let t=D(e),n=k(t,`source`),r=t.scope===void 0?void 0:_a(t.scope),i=Aa(t.removed,`removed`);return{action:va(t.action),...P(`source`,n),...P(`scope`,r),...P(`removed`,i),packages:M(ga)(t.packages)}}function ga(e){let t=D(e);return{source:O(t,`source`),scope:_a(t.scope),filtered:j(t,`filtered`),...P(`installedPath`,k(t,`installedPath`))}}function _a(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function va(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function ya(e){let t=D(e);return{packages:M(ba)(t.packages),totals:Ca(t.totals),diagnostics:M(Ea)(t.diagnostics)}}function ba(e){let t=D(e);return{source:O(t,`source`),scope:xa(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:Ca(t.counts),resources:M(wa)(t.resources),status:Sa(t.status)}}function xa(e){if(e!==`global`&&e!==`project`)throw Error(`Invalid Pi package plugin scope`);return e}function Sa(e){if(e!==`loaded`&&e!==`installed`&&e!==`missing`&&e!==`disabled`)throw Error(`Invalid Pi package plugin status`);return e}function Ca(e){let t=D(e);return{extensions:A(t,`extensions`),skills:A(t,`skills`),prompts:A(t,`prompts`),themes:A(t,`themes`)}}function wa(e){let t=D(e);return{kind:Ta(t.kind),name:O(t,`name`),path:O(t,`path`),relativePath:O(t,`relativePath`)}}function Ta(e){if(e!==`extension`&&e!==`skill`&&e!==`prompt`&&e!==`theme`)throw Error(`Invalid Pi package plugin resource kind`);return e}function Ea(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 Da(e){let t=D(e);return{plugins:M(Oa)(t.plugins)}}function Oa(e){let t=D(e);return{id:O(t,`id`),module:O(t,`module`),source:O(t,`source`),scope:ka(t.scope),machineSpecific:Aa(t.machineSpecific,`machineSpecific`)??!1,enabled:j(t,`enabled`)}}function ka(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEBUI plugin scope`);return e}function Aa(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function ja(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:Na(t.components),release:Ra(t.release),commands:za(t.commands),messages:M(Ba)(t.messages)}}function Ma(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:Pa(t.components),capabilities:Ha(t.capabilities)}}function Na(e){let t=D(e);return{web:Ia(t.web),sessiond:Ia(t.sessiond)}}function Pa(e){let t=D(e);return{web:Fa(t.web),sessiond:Fa(t.sessiond)}}function Fa(e){let t=D(e),n=Va(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:zt(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:O(t,`label`),...P(`runtimeVersion`,k(t,`runtimeVersion`)),available:j(t,`available`),capabilities:Ha(t.capabilities),...P(`activeAgentProfile`,i),...P(`error`,k(t,`error`))}}function Ia(e){let t=D(e);return{component:Va(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`,La(t.installation)),...P(`error`,k(t,`error`))}}function La(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 Ra(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 za(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 Ba(e){let t=D(e);return{id:O(t,`id`),severity:Ua(t.severity),title:O(t,`title`),body:O(t,`body`),...P(`command`,k(t,`command`))}}function Va(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEBUI service component`);return e}function Ha(e){let t=Jt(e);if(t===void 0)throw Error(`Invalid PI WEBUI capabilities`);return t}function Ua(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEBUI status severity`);return e}function Wa(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(eo)(t.options)};if(n===`tree`)return{type:n,tree:Ga(t.tree)};if(n===`done`)return{type:n,...P(`message`,k(t,`message`)),...to(t.session),...P(`promptDraft`,k(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Ga(e){let t=D(e),n=M(Ka)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=Za(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:$a(t.activePathIds,`activePathIds`)}}function Ka(e){let t=D(e);return{id:Qa(t,`id`),parentId:Za(t,`parentId`),kind:qa(t.kind),summary:O(t,`summary`),...P(`timestamp`,k(t,`timestamp`)),...P(`label`,k(t,`label`))}}function qa(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`compaction`:case`branch-summary`:case`model-change`:case`thinking-level-change`:case`session-info`:case`label`:case`custom`:case`other`:return e;default:throw Error(`Invalid session tree node kind`)}}function Ja(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){Xa(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 Xa(t,`aborted`,`session tree navigation result`),{cancelled:n,...P(`editorText`,k(t,`editorText`))}}function Ya(e){let t=D(e);return j(t,`cancelled`)?(Xa(t,`session`,`session fork cancellation result`),{cancelled:!0}):{cancelled:!1,session:vn(t.session)}}function Xa(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function Za(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 Qa(e,t){let n=O(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function $a(e,t){let n=tn(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function eo(e){let t=D(e);return{value:O(t,`value`),label:O(t,`label`),...P(`description`,k(t,`description`))}}function to(e){return e===void 0?{}:{session:vn(e)}}function no(e){if(D(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function ro(e){let t=D(e);return M(io)(t.attachments)}function io(e){let t=D(e);return{path:O(t,`path`),mimeType:O(t,`mimeType`),size:A(t,`size`)}}function ao(e){if(D(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function oo(e){if(typeof e!=`string`)throw Error(`Expected string value`);return e}function so(e){let t=D(e);return{closedProjectIds:M(oo)(t.closedProjectIds)}}function co(e){if(D(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function lo(e){if(D(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function uo(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:tn(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 fo(e){if(D(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function po(e){if(D(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function mo(e){if(D(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function ho(e){if(D(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function go(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 _o(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 vo(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:xo(r)}}function yo(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:bo(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 bo(e){let t={hostname:O(e,`hostname`),localIpv4Addresses:tn(e.localIpv4Addresses,`localIpv4Addresses`),...xo(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 xo(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 So(e){let t=In(e,`project usage count response`);return Rn(t,[`sessionCount`],`project usage count response`),{sessionCount:or(t,`sessionCount`)}}function Co(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 wo(e){let t=D(e),n=D(t.buckets);return{projectPath:O(t,`projectPath`),buckets:{live:Co(n.live),retired:Co(n.retired),archived:Co(n.archived)},total:Co(t.total),generatedAt:O(t,`generatedAt`)}}function To(e){return typeof e==`string`?e:e.id}function Eo(e){return typeof e==`string`?void 0:e.cwd}function Do(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 Oo(e,t,n=`local`){let r=new URLSearchParams,i=Eo(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(To(e))}/messages${a===``?``:`?${a}`}`}function ko(e,t=`local`){let n=new URLSearchParams,r=Eo(e);r!==void 0&&r!==``&&n.set(`cwd`,r);let i=n.toString();return`api/machines/${encodeURIComponent(t)}/sessions/${encodeURIComponent(To(e))}/export${i===``?``:`?${i}`}`}function Ao(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`),Dt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function jo(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),Dt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var F=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function Mo(e){return typeof e==`string`?e:e.id}function No(e){return typeof e==`string`?void 0:e.cwd}function Po(e,t=`local`){return`${F(t)}/sessions/${encodeURIComponent(Mo(e))}`}function I(e,t,n=`local`){return`${Po(e,n)}/${t}`}function Fo(e,t,n=`local`){return`${I(e,t,n)}${Lo(e)}`}function Io(e,t=`local`){return`${Po(e,t)}${Lo(e)}`}function Lo(e){let t=No(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function L(e,t={}){let n=No(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Ro(e){return JSON.stringify({sessions:e.map(zo)})}function zo(e){let t=Mo(e),n=No(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Bo(e){return e===`local`?`api/pi-webui/status`:`${F(e)}/pi-webui/status`}var Vo={piWebUiStatus:(e=`local`)=>T(Bo(e),ja),checkForUpdates:(e=`local`)=>T(`${Bo(e)}?refresh=1`,ja,{cache:`no-store`}),piWebUiRuntime:()=>T(`api/pi-webui/runtime`,Ma),systemInfo:(e=`local`)=>T(`${F(e)}/pi-webui/system-info`,yo),systemMetrics:(e=`local`)=>T(`${F(e)}/pi-webui/system-metrics`,vo,{cache:`no-store`})},Ho={machines:()=>T(`api/machines`,ln),addMachine:e=>T(`api/machines`,un,{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`,dn),runtime:(e,t=!1)=>T(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,fn,t?{cache:`no-store`}:{})};function Uo(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-memory/snapshot?${n.toString()}`}var Wo={snapshot:(e,t=`local`)=>T(Uo(e,t),nn,{cache:`no-store`})};function Go(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-skills/snapshot?${n.toString()}`}var Ko={snapshot:(e,t=`local`)=>T(Go(e,t),an,{cache:`no-store`})};function qo(e){return e===void 0?`api/config`:`${F(e)}/config`}function Jo(e){return e===void 0?`api/plugins`:`${F(e)}/plugins`}var Yo={config:e=>T(qo(e),ta),saveConfig:(e,t)=>T(qo(t),ta,{method:`PUT`,body:JSON.stringify({config:e})})},Xo={plugins:e=>T(Jo(e),Da)};function Zo(e=`local`){return`${F(e)}/models-config`}var Qo={config:(e=`local`)=>T(Zo(e),Er),save:(e,t=`local`)=>T(Zo(t),Pr,{method:`PUT`,body:JSON.stringify(e)}),test:(e,t=`local`)=>T(`${Zo(t)}/test`,Lr,{method:`POST`,body:JSON.stringify(e)}),discover:(e,t=`local`)=>T(`${Zo(t)}/discover`,Fr,{method:`POST`,body:JSON.stringify(e)})};function $o(e=`local`){return`${F(e)}/model-tiers`}var es={settings:(e=`local`)=>T($o(e),Gi),save:(e,t=`local`)=>T($o(t),Gi,{method:`PUT`,body:JSON.stringify({ladder:e})})};function ts(e=`local`){return`${F(e)}/utility-models`}function ns(e,t){if(t===2)return e;let n={};for(let t of xt){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let r=e[t];r===null?n[t]=null:r!==void 0&&(n[t]={provider:r.provider,id:r.id})}return n}var rs={settings:(e=`local`)=>T(ts(e),Mi),save:(e,t,n=`local`)=>T(ts(n),Mi,{method:`PUT`,body:JSON.stringify({settings:ns(e,t)})})};function is(e=`local`){return`${F(e)}/skills`}function as(e,t=`local`){return`${is(t)}?${new URLSearchParams({cwd:e}).toString()}`}var os={list:(e,t=`local`)=>T(as(e,t),Rr),toggle:(e,t=`local`)=>T(is(t),Hr,{method:`PATCH`,body:JSON.stringify(e)}),search:(e,t=`local`)=>T(`${is(t)}/search`,Ur,{method:`POST`,body:JSON.stringify(e)}),install:(e,t=`local`)=>T(`${is(t)}/install`,Hr,{method:`POST`,body:JSON.stringify(e)}),check:(e,t=`local`)=>T(`${is(t)}/check`,Gr,{method:`POST`,body:JSON.stringify(e)}),update:(e,t=`local`)=>T(`${is(t)}/update`,Jr,{method:`POST`,body:JSON.stringify(e)})};function ss(e=``,t){let n=t===void 0?`api/pi-packages`:`${F(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var cs={packages:e=>T(ss(``,e),ma),install:(e,t)=>{let n={source:e};return T(ss(`install`,t),ha,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return T(ss(`remove`,n),ha,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return T(ss(`update`,t),ha,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}};function ls(e=`local`){return`${F(e)}/package-plugins`}function us(e,t=`local`){return`${ls(t)}?${new URLSearchParams({cwd:e}).toString()}`}var ds={list:(e,t=`local`)=>T(us(e,t),ya),mutate:(e,t=`local`)=>T(ls(t),ya,{method:`POST`,body:JSON.stringify(e)})},fs={workspaceActivity:(e=`local`)=>T(`${F(e)}/activity`,ji)},ps={projects:(e=`local`)=>T(`${F(e)}/projects`,M(hn)),addProject:(e,t,n,r=`local`)=>T(`${F(r)}/projects`,hn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}`,ao,{method:`DELETE`}),closeProjectTree:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/close-tree`,so,{method:`POST`}),pinProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/pin`,M(hn),{method:`POST`}),unpinProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/unpin`,M(hn),{method:`POST`}),projectDirectories:(e,t=`local`)=>T(`${F(t)}/project-directories?q=${encodeURIComponent(e)}`,M(mi)),projectUsageCount:(e,t=`local`)=>T(`${F(t)}/sessions/project-usage/count`,So,{method:`POST`,body:JSON.stringify(e)}),projectUsage:(e,t=`local`)=>T(`${F(t)}/sessions/project-usage`,wo,{method:`POST`,body:JSON.stringify(e)})},ms={workspaces:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/workspaces`,M(gn)),deleteWorkspace:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Di,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,hi),workspaceFile:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,_i),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()}`,vi,{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()}`,yi,{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()}`,bi,{method:`POST`})}},hs={sessions:(e,t=`local`)=>T(`${F(t)}/sessions?cwd=${encodeURIComponent(e)}`,M(vn)),reorder:(e,t,n=`local`)=>T(I(e,`reorder`,n),bn,{method:`POST`,body:JSON.stringify(t)}),unreadCatalog:(e=`local`)=>T(`${F(e)}/sessions/unread`,Vn,{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),Vn,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>T(Fo(e,`notifications`,t),Jn),dismissNotification:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss`,r),Jn,{method:`POST`,body:L(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss-all`,r),Jn,{method:`POST`,body:L(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>T(`${F(t)}/sessions`,vn,{method:`POST`,body:JSON.stringify({cwd:e,...n===void 0?{}:{modelPolicy:n}})}),startPlusSession:(e,t,n=`local`)=>T(`${F(n)}/sessions`,vn,{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)}`,wr),sessionDefaultsV2:(e,t=`local`)=>{let n=new URLSearchParams({cwd:e,starterModelPolicyContract:`2`});return T(`${F(t)}/session-defaults?${n.toString()}`,Tr)},updateSessionDefaults:(e,t,n=`local`)=>T(`${F(n)}/session-defaults`,wr,{method:`PUT`,body:JSON.stringify({cwd:e,...t})}),cleanupPreview:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup/preview`,dr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup`,fr,{method:`POST`,body:JSON.stringify(e)}),forceCleanup:(e=`local`)=>T(`${F(e)}/sessions/cleanup/force`,fr,{method:`POST`}),archiveMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/archive`,pr,{method:`POST`,body:Ro(e)}),deleteArchivedMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/delete-archived`,mr,{method:`POST`,body:Ro(e)}),messages:(e,t,n=`local`)=>T(Oo(e,t,n),cn),status:(e,t=`local`)=>T(Fo(e,`status`,t),Tn),systemPrompt:(e,t=`local`)=>T(Fo(e,`system-prompt`,t),Bn),streamSnapshot:(e,t=`local`)=>T(Fo(e,`stream-snapshot`,t),zn),clearQueue:(e,t=`local`)=>T(I(e,`queue/clear`,t),Tn,{method:`POST`,body:L(e)}),dismissWarning:(e,t,n=`local`)=>T(I(e,`warnings/dismiss`,n),Tn,{method:`POST`,body:L(e,{dismissId:t})}),modelPolicy:(e,t=`local`)=>T(Fo(e,`model-policy`,t),En),rememberCurrentModelPolicy:(e,t=`local`)=>T(Fo(e,`model-policy/remember`,t),An,{method:`POST`}),setModelPolicy:(e,t,n=`local`)=>T(I(e,`model-policy`,n),En,{method:`PUT`,body:L(e,{policy:t})}),models:(e,t=`local`)=>T(Fo(e,`models`,t),Cr),setModel:(e,t,n,r=`local`)=>T(I(e,`model`,r),Tn,{method:`POST`,body:L(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>T(I(e,`model/cycle`,n),Tn,{method:`POST`,body:L(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>T(Fo(e,`thinking-levels`,t),Xr),setThinkingLevel:(e,t,n=`local`)=>T(I(e,`thinking-level`,n),Tn,{method:`POST`,body:L(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>T(I(e,`thinking-level/cycle`,t),Tn,{method:`POST`,body:L(e)}),commands:(e,t=`local`)=>T(Fo(e,`commands`,t),M(pi)),prompt:(e,t,n,r=`local`,i)=>T(I(e,`prompt`,r),no,{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),ro,{method:`POST`,body:L(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>T(I(e,`shell`,n),no,{method:`POST`,body:L(e,{text:t})}),runCommand:(e,t,n=`local`)=>T(I(e,`commands/run`,n),Wa,{method:`POST`,body:L(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>T(I(e,`commands/respond`,r),Wa,{method:`POST`,body:L(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>T(I(e,`tree/navigate`,n),Ja,{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),Ja,{method:`POST`,body:L(e,{entryId:t})}),forkFromHere:(e,t,n=`local`)=>T(I(e,`messages/fork`,n),Ya,{method:`POST`,body:L(e,{entryId:t})}),abort:(e,t=`local`)=>T(I(e,`abort`,t),co,{method:`POST`,body:L(e)}),stop:(e,t=`local`)=>T(I(e,`stop`,t),lo,{method:`POST`,body:L(e)}),archive:(e,t=`local`)=>T(I(e,`archive`,t),uo,{method:`POST`,body:L(e)}),archiveWithDescendants:(e,t=`local`)=>T(I(e,`archive-tree`,t),uo,{method:`POST`,body:L(e)}),restore:(e,t=`local`)=>T(I(e,`restore`,t),fo,{method:`POST`,body:L(e)}),deleteArchived:(e,t=`local`)=>T(Io(e,t),po,{method:`DELETE`}),detachParent:(e,t=`local`)=>T(I(e,`detach-parent`,t),mo,{method:`POST`,body:L(e)}),reloadSession:(e,t=`local`)=>T(I(e,`reload`,t),ho,{method:`POST`,body:L(e)}),pin:(e,t=`local`)=>T(I(e,`pin`,t),vn,{method:`POST`,body:L(e)}),unpin:(e,t=`local`)=>T(I(e,`unpin`,t),vn,{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}`}`,ti)},saveApiKey:(e,t,n=`local`)=>T(`${F(n)}/auth/api-key`,no,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>T(`${F(t)}/auth/api-key/interactive`,ni,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>T(`${F(t)}/auth/logout`,no,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>T(`${F(t)}/auth/oauth`,ni,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}`,ni),respondOAuthFlow:(e,t,n,r=`local`)=>T(`${F(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,ni,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ni,{method:`POST`})},gs={terminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,M(Ei)),startTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Ei,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ao,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,ao,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,Ei,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Di,{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${vs(e)}`,M(Di)),getCommandRun:(e,t=`local`)=>_s(e,t),cancelCommandRun:(e,t=`local`)=>T(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Di,{method:`POST`})};async function _s(e,t){let n=await fetch(Dt(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(ys(e)??n.statusText)}return Di(await n.json())}}function vs(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 ys(e){if(!bs(e))return;let t=e.error;return typeof t==`string`?t:void 0}function bs(e){return typeof e==`object`&&!!e}var xs={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(mi)):(r.set(`cwd`,e),T(`${F(n.machineId)}/files?${r.toString()}`,M(mi)))}},Ss={gitStatus:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Si),gitDiff:(e,t,n,r=`local`)=>T(Do(r,e,t,n),Ti)},Cs={...Vo,...Ho,...Wo,learnedSkills:Ko,...es,utilityModels:rs,...Yo,...Xo,...cs,...ds,...fs,...ps,...ms,...hs,...gs,...xs,...Ss};function ws(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(Ot(`${Ds(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function Ts(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(Ot(`${Ds(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function Es(e=`local`){return new WebSocket(Ot(`${Ds(e)}/events`))}function Ds(e){return`api/machines/${encodeURIComponent(e)}`}var Os=`.pi-webui/uploads`,ks=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},As=class extends Error{constructor(e,t){super(Vs(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function js(e){return e?.uploads?.defaultFolder??`.pi-webui/uploads`}function Ms(e,t){return e?.uploads?.defaultFolder??t}function Ns(e,t){let n=Ws(e,`upload destination`,{allowEmpty:!0}),r=Ws(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function Ps(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`,Ao(e,t,n.path,Ls(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Rs(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(vi(Ks(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(qs(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new ks(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function Fs(e,t,n,r={}){let i=r.destinationFolder??`.pi-webui/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:Ns(i,e.name),loaded:0,total:e.size,percent:Bs(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(zs(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 ks;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=Ps(e,t,{path:p.path,file:f},{...Is(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(Us(e,c))throw e;let t=Hs(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 As(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function Is(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 Ls(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Rs(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:Bs(e.loaded,n),lengthComputable:e.lengthComputable}}function zs(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:Bs(i,r),done:n}}function Bs(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Vs(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function Hs(e){return e instanceof Error?e.message:String(e)}function Us(e,t){return t.requested||e instanceof ks}function Ws(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Gs(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 Gs(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Ks(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function qs(e){let t=Js(e);return Ys(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Js(e){try{return Ks(e)}catch{return}}function Ys(e){return typeof e==`object`&&!!e}function Xs(e){return e.closesActionPalette===!0}function Zs(e){return{mode:e.mode,exact:Ac(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function Qs(e){let t=$s(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 $s(e){if(e.policy!==void 0)return Zs(e.policy);let t=e.liveResolved;return t===void 0?{mode:`exact`,exact:{model:{provider:``,id:``},thinkingLevel:``}}:{mode:`exact`,exact:Ac(t)}}function ec(e){let t=e.model?.provider,n=e.model?.id;if(!(t===void 0||n===void 0||!kc(t)||!kc(n))&&kc(e.thinkingLevel))return{model:{provider:t,id:n},thinkingLevel:e.thinkingLevel}}function tc(e){let t=ec(e)??bc(),n=e.starterModelPolicyPreference;return _c(e)?vc(n)?{mode:n.mode,exact:Ac(n.exact),...n.tier===void 0?{}:{tier:n.tier}}:n===void 0?{mode:`tiered`,exact:Ac(t),tier:`standard`}:gc(n,t,n.mode):gc(n,t,`exact`)}function nc(e,t){let n=ec(t);return n===void 0||e.mode===`tiered`||ic(e.exact,n)?e:{...e,exact:Ac(n)}}function rc(e){if(!(e.mode===`tiered`&&e.tier===void 0))return{mode:e.mode,...e.tier===void 0?{}:{tier:e.tier}}}function ic(e,t){return e.model.provider===t.model.provider&&e.model.id===t.model.id&&e.thinkingLevel===t.thinkingLevel}function ac(e,t){return{...e,mode:`tiered`,tier:t}}function oc(e){return{...e,mode:`exact`}}function sc(e,t){let n=t.thinkingLevels.includes(e.exact.thinkingLevel)?e.exact.thinkingLevel:``;return{...e,exact:{model:{...t.model},thinkingLevel:n}}}function cc(e,t){return{...e,exact:{...e.exact,thinkingLevel:t}}}function lc(e,t){if(e.mode===`exact`)return pc(e.exact,t.models)?{mode:`exact`,exact:Ac(e.exact)}:void 0;let n=e.tier;if(!(n===void 0||!t.valid||!Ec(t)||!Dc(t,n)))return{mode:`tiered`,tier:n}}function uc(e,t){return t!==void 0&&lc(e,t)!==void 0}function dc(e,t,n){let r=xc(e);if(yc(t)||e.mode!==`tiered`||Cc(e.exact)||!wc(e.tier)||!Ec(n)||!Dc(n,e.tier))return r;let i=n.ladder?.[e.tier];return i===void 0||!Cc(i)?r:{...r,exact:Ac(i)}}function fc(e,t){let n=e.mode===`exact`?mc(e.exact,t):hc(e,t);if(n.kind===`blocked`)return n;let r=Sc(e.exact);return r===void 0?{kind:`ready`,initialModelPolicy:{mode:e.mode,exact:Ac(e.exact),...e.tier===void 0?{}:{tier:e.tier}},resolved:Ac(n.resolved)}:{kind:`blocked`,reason:r}}function pc(e,t){return Sc(e)===void 0&&t.find(t=>Oc(t.model,e.model))?.thinkingLevels.includes(e.thinkingLevel)===!0}function mc(e,t){let n=Sc(e);if(n!==void 0)return{kind:`blocked`,reason:n};let r=t.models.find(t=>Oc(t.model,e.model));return r===void 0?{kind:`blocked`,reason:`Selected provider/model is unavailable`}:r.thinkingLevels.includes(e.thinkingLevel)?{kind:`ready`,resolved:Ac(e)}:{kind:`blocked`,reason:`Selected thinking level is unsupported by the selected model`}}function hc(e,t){let n=e.tier;if(!wc(n))return{kind:`blocked`,reason:Tc(void 0,t)};let r=Object.hasOwn(t.rows,n)?t.rows[n]:void 0;if(r?.valid!==!0)return{kind:`blocked`,reason:Tc(r,t)};let i=t.ladder?.[n];return i===void 0||!Cc(i)?{kind:`blocked`,reason:Tc(r,t)}:{kind:`ready`,resolved:Ac(i)}}function gc(e,t,n){return{mode:e?.mode??n,exact:Ac(t),...e?.tier===void 0?{}:{tier:e.tier}}}function _c(e){return`starterModelPolicyContractVersion`in e}function vc(e){return e!==void 0&&Object.hasOwn(e,`exact`)}function yc(e){return _c(e)&&vc(e.starterModelPolicyPreference)}function bc(){return{model:{provider:``,id:``},thinkingLevel:``}}function xc(e){return{mode:e.mode,exact:Ac(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function Sc(e){return Cc(e)?void 0:`Choose a provider, model, and thinking level before starting`}function Cc(e){return kc(e.model.provider)&&kc(e.model.id)&&kc(e.thinkingLevel)}function wc(e){return e!==void 0&&bt.includes(e)}function Tc(e,t){return e?.reason!==void 0&&kc(e.reason)?e.reason:t.configError!==void 0&&kc(t.configError)?t.configError:`Selected model tier is unavailable`}function Ec(e){let t=e.ladder;return t!==void 0&&bt.every(e=>Object.hasOwn(t,e))}function Dc(e,t){return Object.hasOwn(e.rows,t)&&e.rows[t].valid}function Oc(e,t){return e.provider===t.provider&&e.id===t.id}function kc(e){return e.trim()!==``}function Ac(e){return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function jc(e){return{kind:`policy-blocked`,scope:e}}function Mc(e,t,n){return{kind:e,message:t,scope:n}}function Nc(e,t,n){if(e===void 0||!Fc(e,t))return;let r=e.kind===`policy-blocked`?n:e.message;return r===void 0||r===``?void 0:r}function Pc(e,t,n){return Fc(e,t)?e.kind!==`policy-blocked`||n!==void 0&&n!==``:!1}function Fc(e,t){return t!==void 0&&e.scope.machineId===t.machineId&&e.scope.workspaceId===t.workspaceId}var Ic={economy:`Economy`,fast:`Fast`,standard:`Standard`,advanced:`Advanced`,capable:`Capable`,frontier:`Frontier`},Lc=Yt;function Rc(e){return`${e.provider}/${e.id}`}function zc(e){let t=e.thinkingLevel.trim()===``?`no thinking level`:e.thinkingLevel;return`${Rc(e.model)} · ${t}`}var Bc={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 Vc(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=Lc.findIndex(t=>t===e);return t===-1?Lc.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,...Bc[n]===void 0?{}:{description:Bc[n]}}))}function Hc(){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 Uc(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],projectSessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,isLoadingSessions:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],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 Wc(e,t){return t?.phase===`active`||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Gc(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function Kc(e,t){return`${e}:${t}`}function qc(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var Jc=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}},Yc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Jc,this.api=n.api??fs,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Xc(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=Zc(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...R(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Xc(e){let t={};for(let n of e.workspaces)Gc(n)&&(t[n.cwd]=n);return t}function Zc(e,t){let n={...e};return Gc(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var Qc=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??Cs,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=el(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||$c(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||$c(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`?$c(n.flow):void 0,a=$c(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=$c(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||$c(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||$c(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 $c(e){return e.prompt?.requestId??e.select?.requestId}function el(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 tl(e){return e.replaceAll(`:`,`.`)}function nl(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 rl(e,t){let n=nl(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function il(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));al(i,r)}function al(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 ol(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:Ns(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:fl(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:fl(0,n),status:`uploading`,startedAt:e.startedAt}}function sl(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 cl(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=dl(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function ll(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,...dl(r),status:`error`,error:t,completedAt:n}}function ul(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,...dl(r),status:`cancelled`,error:n,completedAt:t}}function dl(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function fl(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var pl=tl(`core:workspace.files`),ml=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??Cs,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Fs,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:vl(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`}),il(pl,`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(hl(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),il(pl,`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=ol({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(ul(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:vl(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(sl(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(cl(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 As)||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(gl(t)){let e=ul(n,this.now());return this.setUploadBatch(e),e}let r=_l(t),i=ll(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 hl(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function gl(e){return e instanceof ks}function _l(e){return e instanceof Error?e.message:String(e)}function vl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var yl=tl(`core:workspace.git`),bl=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 Cs.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}),il(yl,`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`}),il(yl,`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([Cs.gitDiff(n.id,r.id,{path:e},i),Cs.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}},xl=3e4,Sl={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},Cl=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??Ko.snapshot,this.timer=n.timer??Sl,this.pollIntervalMs=n.pollIntervalMs??xl}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=wl(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 wl(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalSkills:e.globalSkills,projectSkills:e.projectSkills,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}var Tl=3e4,El={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},Dl=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??Wo.snapshot,this.timer=n.timer??El,this.pollIntervalMs=n.pollIntervalMs??Tl}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=Ol(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 Ol(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalEntries:e.globalEntries,projectEntries:e.projectEntries,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}function kl(e){let t=[],n=[];for(let r of e)Fl(r.index)&&t.push(Pl(r,`staged`,r.index)),Il(r.workingTree)&&n.push(Pl(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function Al(e){let t=kl(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function jl(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 Ml(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 Nl(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function Pl(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function Fl(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function Il(e){return e!==`unmodified`&&e!==`ignored`}var Ll=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 Cs.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:zl(this.getState().machineActivities,r),machineRuntimes:zl(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,...Hc()}),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 Cs.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 Cs.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:Rl(this.getState().machineStatuses,e.id),machineRuntimes:Rl(this.getState().machineRuntimes,e.id),machineActivities:Rl(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 Cs.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 Cs.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 Cs.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=>Cs.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=>Cs.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 Rl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function zl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Bl=`~/workspace`,Vl=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??Cs,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;let r;if(n.length===0){if(r=await this.api.addProject(Bl,void 0,!0,e),!this.isCurrentProjectCatalogOperation(e,t))return;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);this.setState({projects:n,workspacesByProjectId:a}),s&&this.workspaces.clearSelection(),this.onProjectsApplied?.(e),r!==void 0&&await this.workspaces.selectProject(r)}catch(n){this.isCurrentProjectCatalogOperation(e,t)&&this.setState({error:String(n)})}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 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))}},Hl=5e3,Ul=`reconcile selected project catalog`,Wl={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},Gl=class{constructor(e,t){this.getState=e,this.generation=0,this.nextRequestId=0,this.observing=!1,this.listWorkspaces=t.workspaces??ms.workspaces,this.applySnapshot=t.applySnapshot,this.timer=t.timer??Wl,this.pollIntervalMs=t.pollIntervalMs??Hl,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(Ul,e)}catch{}}};function Kl(e,t){return t[e.path]}function ql(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Jl(e,t,n){return Zl(Ql(e,t,n))}function Yl(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function Xl(e){return Zl(Object.values(e??{}))}function Zl(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Ql(e,t,n){return Object.values(n).filter(n=>Yl(e,t,n.cwd))}var $l=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??ms,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])=>!eu(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&&!eu(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(Gc).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 eu(e,t,n){return e.some(e=>Yl(e,t[e.id]??[],n))}var tu=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??Vo,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}),nu(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 nu(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 ru=`pi-webui:cached-new-sessions:v1`,iu=`browserCachedNew`,au=`local`;function ou(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function su(e,t=au,n=ou()){if(e.messageCount!==0||e.archived===!0)return;let r=pu(n).filter(n=>n.id!==e.id||n.machineId!==t);mu([cu(e,t),...r],n)}function cu(e,t=au){return{...e,browserCachedNew:!0,machineId:t}}function lu(e,t=au,n=ou()){mu(pu(n).filter(n=>n.id!==e||n.machineId!==t),n)}function uu(e,t,n=au,r=ou()){let i=new Set(t.map(e=>e.id)),a=pu(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&mu(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function du(e){return e!==void 0&&gu(e)&&e.browserCachedNew===!0}function fu(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:au},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt},...e.creationSource===void 0?{}:{creationSource:e.creationSource}}}function pu(e=ou()){try{let t=e?.getItem(ru);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>hu(e)):[]}catch{return[]}}function mu(e,t=ou()){try{e.length===0?t?.removeItem(ru):t?.setItem(ru,JSON.stringify(e))}catch{}}function hu(e){if(!_u(e))return[];let t=vu(e,`id`),n=vu(e,`path`),r=vu(e,`cwd`),i=vu(e,`created`),a=vu(e,`modified`),o=vu(e,`firstMessage`),s=bu(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=yu(e,`name`),l=yu(e,`parentSessionPath`),u=yu(e,`machineId`)??au,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 gu(e){return iu in e}function _u(e){return typeof e==`object`&&!!e}function vu(e,t){let n=e[t];return typeof n==`string`?n:void 0}function yu(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function bu(e,t){let n=e[t];return typeof n==`number`?n:void 0}function xu(e){return Bu(e.flatMap(Eu)).filter(e=>e.parts.length>0)}function Su(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function Cu(e,t){let n=Mu(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=Yu(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 wu(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,Su(t,n)]}function Tu(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 Eu(e){if(Ou(e))return[e];if(z(e,`role`)===`bashExecution`)return[Cu(Fu(e),e)];let t=Iu(z(e,`role`)),n=Lu(Ju(e,`content`),e),r=t===`user`?ku(n):void 0;if(r!==void 0)return r.map(t=>Cu(t,e));let i=ju(e);if(t===`tool`)return[Cu({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?[Cu({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=Du(e);return c===void 0?s:[...s,Cu(c,e)]}function Du(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return Su(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function Ou(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Ju(e,`parts`))}function ku(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=Au(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 Au(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 ju(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function Mu(e){let t=Nu(Ju(e,`timestamp`)),n=Pu(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function Nu(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 Pu(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 Fu(e){let t=z(e,`command`)??``,n=Yu(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Ju(e,`output`);r!=null&&n.push(``,Zu(r));let i=Ju(e,`exitCode`);i!=null&&n.push(``,`exit ${Zu(i)}`),Yu(e,`cancelled`)===!0&&n.push(``,`cancelled`),Yu(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=z(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
4
4
|
`)}]}}function Iu(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function Lu(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=Ju(e,`arguments`),r=z(e,`id`),i=t===`read`?zu(z(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:Gu(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 Wu(e)}).map(e=>e.type===`text`&&z(t,`role`)===`toolResult`?Ru(e.text,t):e):Wu(e)}function Ru(e,t){let n=z(t,`toolCallId`),r=Ju(t,`content`),i=Ju(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:Yu(t,`isError`)===!0}}function zu(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 Bu(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=Vu(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&&Hu(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function Vu(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 Hu(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=Uu(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 Uu(e){let t=Ju(e,`preview`);if(!qu(t))return;let n=z(t,`diff`),r=z(t,`error`),i=Xu(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 Wu(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:Gu(e)}]:[{type:`text`,text:Zu(e)}]}function Gu(e){if(!qu(e))return Zu(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}: ${Ku(t)}`).join(` · `)}function Ku(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 qu(e){return typeof e==`object`&&!!e}function Ju(e,t){return qu(e)?e[t]:void 0}function z(e,t){let n=Ju(e,t);return typeof n==`string`?n:void 0}function Yu(e,t){let n=Ju(e,t);return typeof n==`boolean`?n:void 0}function Xu(e,t){let n=Ju(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Zu(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Qu=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)}},$u=`pi-webui:prompt-draft:`;function ed(e){return`${$u}${e}`}function td(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function nd(e,t=td()){try{return t?.getItem(ed(e))??``}catch{return``}}function rd(e,t,n=td()){try{t?n?.setItem(ed(e),t):n?.removeItem(ed(e))}catch{}}function id(e,t=td()){try{t?.removeItem(ed(e))}catch{}}function ad(e,t,n=td()){let r=nd(e,n);r!==``&&(rd(t,r,n),id(e,n))}function od(e,t){return Su(`bash`,`${t===!0?`excluded from context
|
|
@@ -1123,7 +1123,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1123
1123
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1124
1124
|
.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; }
|
|
1125
1125
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1126
|
-
`]}};B([x({attribute:!1})],u_.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],u_.prototype,`uploadInput`,void 0),B([S()],u_.prototype,`pendingUpload`,void 0),B([S()],u_.prototype,`destinationFolder`,void 0),B([S()],u_.prototype,`overwrite`,void 0),B([S()],u_.prototype,`createDirs`,void 0),B([S()],u_.prototype,`formError`,void 0),B([S()],u_.prototype,`dragActive`,void 0),u_=B([b(`workspace-files-panel`)],u_);function d_(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 f_(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Ns(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function p_(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function m_(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} · ${D_(t.size)}`}function h_(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function g_(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function __(e){return e==null?[]:Array.from(e)}function v_(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function y_(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function b_(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 x_(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return T_(e.percent)}}function S_(e){return e.status===`uploading`?e.percent:1}function C_(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return T_(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function w_(e){return e.error===void 0?e.response===void 0?`${e.path} · ${D_(e.loaded)} / ${D_(e.total)}`:`Wrote ${e.response.path}`:e.error}function T_(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function E_(){l_(()=>import(`./CodeViewer-
|
|
1126
|
+
`]}};B([x({attribute:!1})],u_.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],u_.prototype,`uploadInput`,void 0),B([S()],u_.prototype,`pendingUpload`,void 0),B([S()],u_.prototype,`destinationFolder`,void 0),B([S()],u_.prototype,`overwrite`,void 0),B([S()],u_.prototype,`createDirs`,void 0),B([S()],u_.prototype,`formError`,void 0),B([S()],u_.prototype,`dragActive`,void 0),u_=B([b(`workspace-files-panel`)],u_);function d_(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 f_(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Ns(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function p_(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function m_(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} · ${D_(t.size)}`}function h_(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function g_(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function __(e){return e==null?[]:Array.from(e)}function v_(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function y_(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function b_(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 x_(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return T_(e.percent)}}function S_(e){return e.status===`uploading`?e.percent:1}function C_(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return T_(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function w_(e){return e.error===void 0?e.response===void 0?`${e.path} · ${D_(e.loaded)} / ${D_(e.total)}`:`Wrote ${e.response.path}`:e.error}function T_(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function E_(){l_(()=>import(`./CodeViewer-DUqxkZ3h.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function D_(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`${O_(t)} KB`;let n=t/1024;return n<1024?`${O_(n)} MB`:`${O_(n/1024)} GB`}function O_(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var k_=2e3,A_=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 Vo.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)},k_))}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 Vo.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">
|
|
1127
1127
|
<p class="error-text">Failed to load system information: ${this.error}</p>
|
|
1128
1128
|
<button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
|
|
1129
1129
|
</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">
|
|
@@ -1377,7 +1377,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1377
1377
|
<div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
|
|
1378
1378
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
1379
1379
|
</section>
|
|
1380
|
-
`}function U_(){l_(()=>import(`./UnifiedDiffViewer-
|
|
1380
|
+
`}function U_(){l_(()=>import(`./UnifiedDiffViewer-CqMCpp0S.js`),[],import.meta.url)}function W_(){l_(()=>Promise.resolve().then(()=>cN),void 0,import.meta.url)}function G_(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function K_(e){let t=q_(e);return g`
|
|
1381
1381
|
<p class="summary">
|
|
1382
1382
|
<span class="summary-branch">${t.branch}</span>
|
|
1383
1383
|
${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
|
|
@@ -2823,18 +2823,20 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
2823
2823
|
${e}</tr>
|
|
2824
2824
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
2825
2825
|
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${CT(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=wT(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+CT(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=wT(e);if(i===null)return CT(n);e=i;let a=`<img src="${e}" alt="${CT(n)}"`;return t&&(a+=` title="${CT(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:CT(e.text)}},FT=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},IT=class e{options;renderer;textRenderer;constructor(e){this.options=e||cw,this.options.renderer=this.options.renderer||new PT,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new FT}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},LT=class{options;block;constructor(e){this.options=e||cw}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?NT.lex:NT.lexInline}provideParser(e=this.block){return e?IT.parse:IT.parseInline}},RT=new class{defaults=sw();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=IT;Renderer=PT;TextRenderer=FT;Lexer=NT;Tokenizer=MT;Hooks=LT;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new PT(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new MT(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new LT;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];LT.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&<.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return NT.lex(e,t??this.defaults)}parser(e,t){return IT.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?NT.lex:NT.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?IT.parse:IT.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?NT.lex:NT.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?IT.parse:IT.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
|
|
2826
|
-
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+CT(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function G(e,t){return RT.parse(e,t)}G.options=G.setOptions=function(e){return RT.setOptions(e),G.defaults=RT.defaults,lw(G.defaults),G},G.getDefaults=sw,G.defaults=cw,G.use=function(...e){return RT.use(...e),G.defaults=RT.defaults,lw(G.defaults),G},G.walkTokens=function(e,t){return RT.walkTokens(e,t)},G.parseInline=RT.parseInline,G.Parser=IT,G.parser=IT.parse,G.Renderer=PT,G.TextRenderer=FT,G.Lexer=NT,G.lexer=NT.lex,G.Tokenizer=MT,G.Hooks=LT,G.parse=G,G.options,G.setOptions,G.use,G.walkTokens,G.parseInline,IT.parse,NT.lex;var zT=new G.Renderer;zT.html=({text:e})=>JT(e);var BT=1600,VT=6e6,HT=8,UT=new Map,WT=0;function GT(e,t={}){let n=t.cache!==!1;if(n){let t=UT.get(e);if(t!==void 0)return UT.delete(e),UT.set(e,t),t.html}let r=YT(G.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:zT}));return n&&KT(e,r),r}function KT(e,t){let n=e.length+t.length;if(n>VT/HT)return;let r=UT.get(e);r!==void 0&&(UT.delete(e),WT-=r.chars),UT.set(e,{html:t,chars:n}),WT+=n,qT()}function qT(){for(;UT.size>1&&(UT.size>BT||WT>VT);){let e=UT.entries().next();if(e.done===!0)break;let[t,n]=e.value;UT.delete(t),WT-=n.chars}}function JT(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function YT(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`)&&!XT(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),t.innerHTML}function XT(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var
|
|
2826
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+CT(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function G(e,t){return RT.parse(e,t)}G.options=G.setOptions=function(e){return RT.setOptions(e),G.defaults=RT.defaults,lw(G.defaults),G},G.getDefaults=sw,G.defaults=cw,G.use=function(...e){return RT.use(...e),G.defaults=RT.defaults,lw(G.defaults),G},G.walkTokens=function(e,t){return RT.walkTokens(e,t)},G.parseInline=RT.parseInline,G.Parser=IT,G.parser=IT.parse,G.Renderer=PT,G.TextRenderer=FT,G.Lexer=NT,G.lexer=NT.lex,G.Tokenizer=MT,G.Hooks=LT,G.parse=G,G.options,G.setOptions,G.use,G.walkTokens,G.parseInline,IT.parse,NT.lex;var zT=new G.Renderer;zT.html=({text:e})=>JT(e);var BT=1600,VT=6e6,HT=8,UT=new Map,WT=0;function GT(e,t={}){let n=t.cache!==!1;if(n){let t=UT.get(e);if(t!==void 0)return UT.delete(e),UT.set(e,t),t.html}let r=YT(G.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:zT}));return n&&KT(e,r),r}function KT(e,t){let n=e.length+t.length;if(n>VT/HT)return;let r=UT.get(e);r!==void 0&&(UT.delete(e),WT-=r.chars),UT.set(e,{html:t,chars:n}),WT+=n,qT()}function qT(){for(;UT.size>1&&(UT.size>BT||WT>VT);){let e=UT.entries().next();if(e.done===!0)break;let[t,n]=e.value;UT.delete(t),WT-=n.chars}}function JT(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function YT(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`)&&!XT(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),t.innerHTML}function XT(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}function ZT({text:e,live:t}){return t&&e.length>=24e3}var QT=class extends y{constructor(...e){super(...e),this.text=``,this.live=!1,this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`.code-copy-button`);if(!(t instanceof HTMLButtonElement))return;let n=t.closest(`.code-block-wrapper`);if(!(n instanceof HTMLElement))return;let r=n.querySelector(`pre code`);r instanceof HTMLElement&&this.copyCode(r.textContent,t)}}render(){return ZT(this)?g`<div class="formatted plain" dir="auto">${this.text}</div>`:g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${ow(GT(this.text,{cache:!this.live}))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll(`pre`).forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains(`code-block-wrapper`)===!0||!(e.querySelector(`code`)instanceof HTMLElement))return;let t=document.createElement(`div`);t.className=`code-block-wrapper`;let n=document.createElement(`button`);n.type=`button`,n.className=`code-copy-button`,n.title=`Copy code block`,n.setAttribute(`aria-label`,`Copy code block`);let r=document.createElement(`span`);r.setAttribute(`aria-hidden`,`true`),r.textContent=`⧉`,n.append(r),e.before(t),t.append(e,n)})}async copyCode(e,t){let n=await uC(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=[t_,h`
|
|
2827
|
+
.formatted.plain { white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
|
|
2828
|
+
`]}};B([x()],QT.prototype,`text`,void 0),B([x({type:Boolean})],QT.prototype,`live`,void 0),QT=B([b(`formatted-text`)],QT);var $T=180,eE=class extends y{constructor(...e){super(...e),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){let e=this.execution;if(e===void 0)return null;let t=nE(e.args),n=iE(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:aE(i),o=n!==void 0&&r?.diff!==void 0&&n!==r.diff,s=e.status===`error`?e.resultText:r?.error,c=i===void 0?e.resultText:void 0,l=tE(e,t);return g`
|
|
2827
2829
|
<section class=${`tool-card ${e.status}`}>
|
|
2828
2830
|
<div class="tool-header">
|
|
2829
2831
|
<div class="tool-title">
|
|
2830
|
-
<span class="status-icon" aria-hidden="true">${
|
|
2832
|
+
<span class="status-icon" aria-hidden="true">${lE(e.status)}</span>
|
|
2831
2833
|
<strong>${e.toolName}</strong>
|
|
2832
2834
|
${this.renderHeaderTarget(l)}
|
|
2833
2835
|
</div>
|
|
2834
2836
|
<div class="tool-meta">
|
|
2835
|
-
${
|
|
2837
|
+
${rE(e)===void 0?null:g`<span>${rE(e)}</span>`}
|
|
2836
2838
|
${a===void 0?null:g`<span class="diff-stats"><b class="added">+${a.added}</b><span>/</span><b class="removed">-${a.removed}</b></span>`}
|
|
2837
|
-
<span class="status-label">${
|
|
2839
|
+
<span class="status-label">${uE(e.status)}</span>
|
|
2838
2840
|
</div>
|
|
2839
2841
|
</div>
|
|
2840
2842
|
|
|
@@ -2859,7 +2861,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2859
2861
|
`}
|
|
2860
2862
|
</details>
|
|
2861
2863
|
`}renderDiffBody(e,t,n){let r=e.split(`
|
|
2862
|
-
`),i=!this.showFullDiff&&r.length
|
|
2864
|
+
`),i=!this.showFullDiff&&r.length>$T,a=i?r.slice(0,$T):r;return g`
|
|
2863
2865
|
<details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
|
|
2864
2866
|
<summary>
|
|
2865
2867
|
<span>${t}</span>
|
|
@@ -2870,7 +2872,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2870
2872
|
<span>${i?`Showing ${String(a.length)} of ${String(r.length)} lines`:`Full diff`}</span>
|
|
2871
2873
|
<button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?`Copied`:`Copy diff`}</button>
|
|
2872
2874
|
</div>
|
|
2873
|
-
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${
|
|
2875
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${oE(e)}>${e}</span>`)}</code></pre>
|
|
2874
2876
|
${i?g`
|
|
2875
2877
|
<button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
2876
2878
|
Show all ${String(r.length)} diff lines
|
|
@@ -2921,20 +2923,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2921
2923
|
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
2922
2924
|
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
2923
2925
|
.show-more { justify-self: start; }
|
|
2924
|
-
`}};B([x({attribute:!1})]
|
|
2925
|
-
`))
|
|
2926
|
+
`}};B([x({attribute:!1})],eE.prototype,`execution`,void 0),B([S()],eE.prototype,`showFullDiff`,void 0),B([S()],eE.prototype,`copied`,void 0),B([S()],eE.prototype,`diffOpen`,void 0),eE=B([b(`tool-execution-view`)],eE);function tE(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=pE(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function nE(e){return pE(e,`path`)??pE(e,`file_path`)}function rE(e){if(e.toolName!==`edit`)return;let t=fE(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof fE(e.args,`oldText`)==`string`&&typeof fE(e.args,`newText`)==`string`)return`1 edit`}function iE(e){return pE(e,`diff`)}function aE(e){let t=0,n=0;for(let r of e.split(`
|
|
2927
|
+
`))sE(r)?t++:cE(r)&&n++;return{added:t,removed:n}}function oE(e){return sE(e)?`added`:cE(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function sE(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function cE(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function lE(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function uE(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function dE(e){return typeof e==`object`&&!!e}function fE(e,t){return dE(e)?e[t]:void 0}function pE(e,t){let n=fE(e,t);return typeof n==`string`?n:void 0}var mE=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),hE=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function gE(e){return g`
|
|
2926
2928
|
<svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2927
2929
|
<path d="m9 18 6-6-6-6"></path>
|
|
2928
2930
|
</svg>
|
|
2929
|
-
`}function
|
|
2931
|
+
`}function _E(){return g`
|
|
2930
2932
|
<svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2931
2933
|
<path d="M6 6l12 12"></path>
|
|
2932
2934
|
<path d="M18 6 6 18"></path>
|
|
2933
2935
|
</svg>
|
|
2934
|
-
`}function
|
|
2936
|
+
`}function vE(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`machineId`)==`string`&&typeof Reflect.get(e,`cwd`)==`string`&&typeof Reflect.get(e,`sessionId`)==`string`}function yE(e){return bE(e,0,100)}function bE(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function xE(e,t){let n=[`steer`,`followUp`].flatMap(e=>{let n=t.filter(t=>t.kind===e);return n.length===0?[]:[{source:`server`,kind:e,heading:e===`steer`?`Steered`:`Follow-up`,detail:e===`steer`?`Sent together at the next turn`:`Sent together after the agent finishes`,messages:n}]});return[e.length===0?void 0:{source:`client`,heading:`Queued until session starts`,detail:`Will send once the backend session is ready`,messages:e},...n].filter(e=>e!==void 0)}function SE(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function CE(e){return e===void 0||e===``?`tool output`:`${e} output`}function wE(e){return`m:${String(e)}`}function TE(e){return`g:${String(e)}`}function EE(e){return`e:${String(e)}`}function DE(e){return`g:${String(e)}`}function OE(e){return e?`msg event-group live`:`msg event-group`}function kE(e){return e?`live events`:`events`}function AE(e,t,n){return e.some(e=>e.source===`server`&&e.messages.length>0)&&t&&n}function jE(e){return e.filter(e=>e.source===`server`&&e.messages.length>0).flatMap(e=>e.messages.map(e=>e.text)).join(`
|
|
2935
2937
|
|
|
2936
|
-
`)}function
|
|
2937
|
-
`)}function
|
|
2938
|
+
`)}function ME(e){return(e?.warnings??[]).map(e=>({severity:e.severity,severityClass:`session-warning ${e.severity}`,message:e.message,...e.source===void 0?{}:{source:e.source},...e.path===void 0?{}:{path:e.path},...e.dismiss===void 0?{}:{dismissId:e.dismiss.id}}))}function NE(e){return e>=50?`generation-rate very-fast`:e>=30?`generation-rate fast`:e>=15?`generation-rate moderate`:`generation-rate slow`}function PE(e){if(e===void 0)return{afterStatus:[],trailing:[]};let t=e.contextUsage,n=t?t.percent==null?`context ${yx(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${yx(t.contextWindow)}`:`context unknown`,r=e.generation;return{afterStatus:!e.isStreaming||r===void 0||!Number.isFinite(r.outputTokens)||r.outputTokens<=0?[]:[{label:r.estimated===!0?`Estimated received tokens`:`Received tokens`,text:`↓ ${yx(r.outputTokens)}`},...r.tokensPerSecond===void 0||!Number.isFinite(r.tokensPerSecond)||r.tokensPerSecond<=0?[]:[{label:r.estimated===!0?`Estimated generation speed`:`Generation speed`,text:`${r.tokensPerSecond.toFixed(1)} t/s`,className:NE(r.tokensPerSecond)}]],trailing:[{label:`Input tokens`,text:`↑${yx(e.tokens.input)}`},{label:`Output tokens`,text:`↓${yx(e.tokens.output)}`},{label:`Context usage`,text:n},{label:`Session cost`,text:bx(e.cost)},...e.pendingMessageCount>0?[{label:`Queued messages`,text:`${String(e.pendingMessageCount)} queued`}]:[]]}}function FE(e,t){if(!Number.isInteger(e)||e<=0)return;let n=`${String(e)} ${e===1?`warning`:`warnings`}`;return{countText:String(e),accessibleLabel:t?`Minimise ${n}`:`Show ${n} in the warning area`}}function IE(e){let t=e.meta?.timestamp,n=[t===void 0?void 0:zE(t),BE(e)].filter(e=>e!==void 0&&e!==``);return n.length===0?`No Pi message metadata available`:n.join(` · `)}function LE(e,t){return!t.enabled||t.busy||e.role!==`user`?{}:{...e.previousAssistantEntryId===void 0?{}:{editFromHereEntryId:e.previousAssistantEntryId},...e.canFork===!0&&e.entryId!==void 0?{forkEntryId:e.entryId}:{}}}function RE(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2939
|
+
`)}function zE(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return mE.format(t)}function BE(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var K=class extends y{constructor(...e){super(...e),this.messages=[],this.sessionId=``,this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.clientQueuedMessages=[],this.warningCount=0,this.warningsExpanded=!1,this.canClearServerQueue=!1,this.canMessageActions=!1,this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedNotificationTargetKeys=new Set,this.disclosures=new $S,this.scrollController=new FC,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.sessionInfoOpen=!1,this._minimapMarkers=[],this._minimapVisible=!1,this._minimapViewport={scrollRatio:0,viewportRatio:1,visible:!1},this._minimapLoadedPercent=100,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onImageLoad=()=>{this.pinnedToBottom&&this.scrollToBottom()},this.openImageZoom=(e,t)=>{this.zoomedImage={src:e,alt:t}},this.closeImageZoom=()=>{this.zoomedImage!==void 0&&(this.zoomedImage=void 0)},this.onImageZoomDialogClick=e=>{e.target===this.imageZoomDialog&&this.closeImageZoom()},this.onPageHide=()=>{this.saveScrollPosition()},this.handleClearServerQueue=()=>{this.onClearServerQueue?.()},this.handleCopyAllQueuedMessages=()=>{this.copyAllQueuedMessages()},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},this.handleUsageToggle=()=>{this.sessionInfoOpen=!this.sessionInfoOpen},this.handleUsageKeydown=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.sessionInfoOpen=!this.sessionInfoOpen)},this.closeSessionInfoPopover=()=>{this.sessionInfoOpen&&(this.sessionInfoOpen=!1,this.removePopoverOutsideListener(),this.requestUpdate())},this.handlePopoverKeydown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeSessionInfoPopover(),this.focusUsageToggle())},this.onPopoverGlobalClick=e=>{this.handlePopoverClickOutside(e)},this.popoverGlobalListenerAttached=!1}focusUsageToggle(){this.renderRoot!==void 0&&this.renderRoot.querySelector(`.usage-toggle`)?.focus()}handlePopoverClickOutside(e){let t=this.renderRoot.querySelector(`.session-info-popover`),n=this.renderRoot.querySelector(`.usage-toggle`);if(t===null||n===null)return;let r=e.target;r instanceof Node&&!t.contains(r)&&!n.contains(r)&&this.closeSessionInfoPopover()}ensurePopoverOutsideListener(){this.popoverGlobalListenerAttached||typeof window>`u`||(this.popoverGlobalListenerAttached=!0,window.addEventListener(`click`,this.onPopoverGlobalClick,!0))}removePopoverOutsideListener(){this.popoverGlobalListenerAttached&&(this.popoverGlobalListenerAttached=!1,!(typeof window>`u`)&&window.removeEventListener(`click`,this.onPopoverGlobalClick,!0))}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),window.addEventListener(`pagehide`,this.onPageHide),window.visualViewport?.addEventListener(`resize`,this.onViewportResize),this._setupResizeObserver()}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}_setupResizeObserver(){if(this._resizeObserver!==void 0)return;let e=this.chat;e&&(this._resizeObserver=new ResizeObserver(()=>{this._requestMinimapMeasure()}),this._resizeObserver.observe(e))}disconnectedCallback(){this.removePopoverOutsideListener(),this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.minimapViewportFrame!==void 0&&cancelAnimationFrame(this.minimapViewportFrame),this._minimapMeasureTimer!==void 0&&(clearTimeout(this._minimapMeasureTimer),this._minimapMeasureTimer=void 0),this._resizeObserver!==void 0&&(this._resizeObserver.disconnect(),this._resizeObserver=void 0),window.removeEventListener(`resize`,this.onViewportResize),window.removeEventListener(`pagehide`,this.onPageHide),window.visualViewport?.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!=`string`||e===``||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,this.sessionInfoOpen=!1,this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this._minimapMarkers=[],this._minimapVisible=!1,this._minimapViewport={scrollRatio:0,viewportRatio:1,visible:!1},this._minimapLoadedPercent=100,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has(`sessionId`)?(this.savePreviousSessionScrollPosition(e.get(`sessionId`)),this.prepareSessionUiState()):e.has(`notificationInbox`)&&this.notificationTargetChanged(e.get(`notificationInbox`))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0),e.has(`messages`)&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){let t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has(`loadingMore`)&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has(`hasMore`)&&!this.hasMore&&(this.loadMoreRequested=!1),e.has(`sessionId`)&&this.restoreScrollPosition(),!e.has(`sessionId`)&&e.has(`messages`)&&this.pinnedToBottom&&this.scrollToBottom(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`messageTotal`)||e.has(`hasMore`)||e.has(`loadingMore`))&&(this.scheduleMinimapViewportUpdate(),this._requestMinimapMeasure()),e.has(`messages`)&&!e.has(`sessionId`)&&this._updateMinimapViewport(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.continuePendingScrollRestore(),(e.has(`messages`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.requestLoadMoreIfNeeded(),e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget(),e.has(`zoomedImage`)&&this.syncImageZoomDialog(),this.syncPopoverOutsideListener()}syncPopoverOutsideListener(){this.sessionInfoOpen?this.ensurePopoverOutsideListener():this.removePopoverOutsideListener()}syncImageZoomDialog(){let e=this.imageZoomDialog;e!==void 0&&(this.zoomedImage!==void 0&&!e.open?e.showModal():this.zoomedImage===void 0&&e.open&&e.close())}notificationTargetChanged(e){let t=this.notificationInbox;return!vE(e)||t===void 0?e!==t:nm(e)!==nm(t)}render(){let e=this.groupedMessages();return g`
|
|
2938
2940
|
${this.renderTopNotices()}
|
|
2939
2941
|
${this.renderNotificationLiveRegions()}
|
|
2940
2942
|
<div class="chat-wrap" style=${this._minimapVisible&&this.messages.length>0&&this.messageTotal>0?`--pi-minimap-right:36px`:``}>
|
|
@@ -2969,7 +2971,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2969
2971
|
aria-expanded=${String(!a)}
|
|
2970
2972
|
aria-controls="session-notification-list"
|
|
2971
2973
|
@click=${()=>{this.toggleNotificationTray(e,a)}}
|
|
2972
|
-
>${
|
|
2974
|
+
>${gE(a)}</button>
|
|
2973
2975
|
</div>
|
|
2974
2976
|
</header>
|
|
2975
2977
|
<div class="notification-list" id="session-notification-list" ?hidden=${a}>
|
|
@@ -2981,7 +2983,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2981
2983
|
<div class="notification-metadata">
|
|
2982
2984
|
<strong class="notification-severity">${n}</strong>
|
|
2983
2985
|
<span aria-hidden="true">·</span>
|
|
2984
|
-
<time datetime=${t.receivedAt}>${
|
|
2986
|
+
<time datetime=${t.receivedAt}>${hE.format(new Date(t.receivedAt))}</time>
|
|
2985
2987
|
</div>
|
|
2986
2988
|
<p class="notification-message" dir="auto">${t.message}</p>
|
|
2987
2989
|
${r===void 0?null:g`<p class="notification-truncated">${r}</p>`}
|
|
@@ -2992,7 +2994,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2992
2994
|
title="Dismiss notification"
|
|
2993
2995
|
?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
|
|
2994
2996
|
@click=${()=>{this.dismissNotification(t.id)}}
|
|
2995
|
-
>${
|
|
2997
|
+
>${_E()}</button>
|
|
2996
2998
|
</article>
|
|
2997
2999
|
`})}
|
|
2998
3000
|
</div>
|
|
@@ -3000,7 +3002,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3000
3002
|
`}renderNotificationLiveRegions(){let e=this.notificationInbox?.sessionId===this.sessionId?this.notificationInbox.announcements:[],t=e.filter(e=>e.severity!==`error`),n=e.filter(e=>e.severity===`error`);return g`
|
|
3001
3003
|
<div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${ex(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Zp(e)}</span>`)}</div>
|
|
3002
3004
|
<div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${ex(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Zp(e)}</span>`)}</div>
|
|
3003
|
-
`}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=im(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=tm(t.notifications,e),r=nm(t);this.pendingNotificationFocus={chatKey:r,focusTarget:n},n.kind===`header`&&(this.retainedEmptyNotificationTrayTargetKey=r),this.onDismissNotification(e)}dismissAllNotifications(){let e=this.notificationInbox;if(e===void 0||this.onDismissAllNotifications===void 0)return;let t=nm(e);this.pendingNotificationFocus={chatKey:t,focusTarget:{kind:`header`}},this.retainedEmptyNotificationTrayTargetKey=t,this.onDismissAllNotifications()}releaseEmptyNotificationTray(e){let t=e.currentTarget,n=e.relatedTarget;if(t instanceof HTMLElement&&n instanceof Node&&t.contains(n)||this.pendingNotificationFocus!==void 0)return;let r=this.notificationInbox;r!==void 0&&this.retainedEmptyNotificationTrayTargetKey===nm(r)&&Qp(r)===0&&(this.retainedEmptyNotificationTrayTargetKey=void 0)}focusPendingNotificationTarget(){let e=this.pendingNotificationFocus;this.pendingNotificationFocus=void 0;let t=this.notificationInbox;if(e===void 0||t===void 0||nm(t)!==e.chatKey)return;let n=e.focusTarget;if(n.kind===`header`){this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus();return}let r=Array.from(this.renderRoot.querySelectorAll(`[data-notification-id]`)).find(e=>e.dataset.notificationId===n.notificationId);if(r!==void 0){r.focus();return}Qp(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=
|
|
3005
|
+
`}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=im(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=tm(t.notifications,e),r=nm(t);this.pendingNotificationFocus={chatKey:r,focusTarget:n},n.kind===`header`&&(this.retainedEmptyNotificationTrayTargetKey=r),this.onDismissNotification(e)}dismissAllNotifications(){let e=this.notificationInbox;if(e===void 0||this.onDismissAllNotifications===void 0)return;let t=nm(e);this.pendingNotificationFocus={chatKey:t,focusTarget:{kind:`header`}},this.retainedEmptyNotificationTrayTargetKey=t,this.onDismissAllNotifications()}releaseEmptyNotificationTray(e){let t=e.currentTarget,n=e.relatedTarget;if(t instanceof HTMLElement&&n instanceof Node&&t.contains(n)||this.pendingNotificationFocus!==void 0)return;let r=this.notificationInbox;r!==void 0&&this.retainedEmptyNotificationTrayTargetKey===nm(r)&&Qp(r)===0&&(this.retainedEmptyNotificationTrayTargetKey=void 0)}focusPendingNotificationTarget(){let e=this.pendingNotificationFocus;this.pendingNotificationFocus=void 0;let t=this.notificationInbox;if(e===void 0||t===void 0||nm(t)!==e.chatKey)return;let n=e.focusTarget;if(n.kind===`header`){this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus();return}let r=Array.from(this.renderRoot.querySelectorAll(`[data-notification-id]`)).find(e=>e.dataset.notificationId===n.notificationId);if(r!==void 0){r.focus();return}Qp(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=ME(this.status);return!this.warningsVisible||e.length===0?null:g`
|
|
3004
3006
|
<aside class="session-warnings" role="alert" aria-live="polite">
|
|
3005
3007
|
${e.map(e=>{let t=e.dismissId;return g`
|
|
3006
3008
|
<div class=${e.severityClass}>
|
|
@@ -3081,7 +3083,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3081
3083
|
<img class="image-zoom-full" src=${this.zoomedImage.src} alt=${this.zoomedImage.alt} />
|
|
3082
3084
|
`}
|
|
3083
3085
|
</dialog>
|
|
3084
|
-
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=aC(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase===`active`}renderActivityDock(){if(this.isSendingPrompt)return this.renderActivityDockContent(`Sending your message…`,!0);let e=this.activityState();return e===void 0?null:this.renderActivityDockContent(this.activityText(e),e!==`idle`||this.activity?.phase===`active`)}renderActivityDockContent(e,t){let n=
|
|
3086
|
+
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=aC(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase===`active`}renderActivityDock(){if(this.isSendingPrompt)return this.renderActivityDockContent(`Sending your message…`,!0);let e=this.activityState();return e===void 0?null:this.renderActivityDockContent(this.activityText(e),e!==`idle`||this.activity?.phase===`active`)}renderActivityDockContent(e,t){let n=PE(this.status),r=FE(this.warningCount,this.warningsExpanded),i=n.trailing.length>0,a=this.status?tw(this.status):``,o=i?`session-info-popover-${this.sessionId}`:void 0;return g`
|
|
3085
3087
|
<div class=${t?`activity-dock active`:`activity-dock`}>
|
|
3086
3088
|
${r===void 0||this.onToggleWarnings===void 0?null:g`
|
|
3087
3089
|
<button
|
|
@@ -3124,7 +3126,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3124
3126
|
`:null}
|
|
3125
3127
|
${this.renderSessionInfoPopover()}
|
|
3126
3128
|
</div>
|
|
3127
|
-
`}renderActivityMetrics(e){return e.map(e=>g`<span class=${e.className===void 0?`activity-metric`:`activity-metric ${e.className}`} title=${e.label}>${e.text}</span>`)}renderQueuedMessages(){let e=
|
|
3129
|
+
`}renderActivityMetrics(e){return e.map(e=>g`<span class=${e.className===void 0?`activity-metric`:`activity-metric ${e.className}`} title=${e.label}>${e.text}</span>`)}renderQueuedMessages(){let e=xE(this.clientQueuedMessages,this.status?.queuedMessages??[]),t=e.find(e=>e.source===`client`),n=e.filter(e=>e.source===`server`),r=n.length>0,i=AE(e,this.canClearServerQueue,this.onClearServerQueue!==void 0);return g`
|
|
3128
3130
|
${t===void 0?null:this.renderQueuedMessageList(t)}
|
|
3129
3131
|
${r||i?g`
|
|
3130
3132
|
<div class="queued-actions">
|
|
@@ -3137,7 +3139,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3137
3139
|
</div>
|
|
3138
3140
|
`:null}
|
|
3139
3141
|
${n.map(e=>this.renderQueuedMessageList(e))}
|
|
3140
|
-
`}async copyAllQueuedMessages(){await uC(
|
|
3142
|
+
`}async copyAllQueuedMessages(){await uC(jE(xE(this.clientQueuedMessages,this.status?.queuedMessages??[]).filter(e=>e.source===`server`)))}renderQueuedMessageList(e){return g`
|
|
3141
3143
|
<aside class="queued-messages" aria-live="polite">
|
|
3142
3144
|
<div class="queued-header">
|
|
3143
3145
|
<div class="queued-heading">
|
|
@@ -3172,7 +3174,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3172
3174
|
<span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
|
|
3173
3175
|
${this.pendingMessageCount>0?g`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?`message`:`messages`}</small>`:null}
|
|
3174
3176
|
</aside>
|
|
3175
|
-
`:null}activityState(){let e=this.status;return e===void 0?this.activity?.label:e.isCompacting?`compacting`:e.isBashRunning?`bash`:e.isStreaming?`running`:e.pendingMessageCount>0?`queued`:`idle`}activityText(e){let t=this.activity;return t===void 0||e!==`idle`&&t.phase===`idle`?e:t.detail!==void 0&&t.detail!==``?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){return!this.messages.length||this.messageTotal<=0?null:(this._minimapLoadedPercent=this.hasMore?
|
|
3177
|
+
`:null}activityState(){let e=this.status;return e===void 0?this.activity?.label:e.isCompacting?`compacting`:e.isBashRunning?`bash`:e.isStreaming?`running`:e.pendingMessageCount>0?`queued`:`idle`}activityText(e){let t=this.activity;return t===void 0||e!==`idle`&&t.phase===`idle`?e:t.detail!==void 0&&t.detail!==``?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){return!this.messages.length||this.messageTotal<=0?null:(this._minimapLoadedPercent=this.hasMore?yE(this.messages.length/this.conversationDisplayTotal()*100):100,g`
|
|
3176
3178
|
<chat-minimap
|
|
3177
3179
|
.scrollRatio=${this._minimapViewport.scrollRatio}
|
|
3178
3180
|
.viewportRatio=${this._minimapViewport.viewportRatio}
|
|
@@ -3193,7 +3195,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3193
3195
|
${r?null:this.renderMessageHeader(e,String(t))}
|
|
3194
3196
|
${e.parts.map(t=>this.renderPart(t,e,n))}
|
|
3195
3197
|
</article>
|
|
3196
|
-
`}renderToolImageOutput(e,t,n){let r=
|
|
3198
|
+
`}renderToolImageOutput(e,t,n){let r=CE(n);return g`
|
|
3197
3199
|
${this.renderScrollMarker(this.messageScrollMarkerId(t))}
|
|
3198
3200
|
<article class="msg tool-image-output" data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
|
|
3199
3201
|
${this.renderMessageHeader(e,String(t),r)}
|
|
@@ -3201,9 +3203,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3201
3203
|
</article>
|
|
3202
3204
|
`}isToolExecutionOnlyMessage(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`toolExecution`)}renderMessageGroup(e,t,n,r){let i=this.groupDisclosureKey(t,n,r),a=this.disclosures.isOpen(i,r);return g`
|
|
3203
3205
|
${this.renderScrollMarker(this.groupScrollMarkerId(n))}
|
|
3204
|
-
<details class=${
|
|
3206
|
+
<details class=${OE(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
|
|
3205
3207
|
<summary>
|
|
3206
|
-
<b class="label">${
|
|
3208
|
+
<b class="label">${kE(r)}</b>
|
|
3207
3209
|
<span>${oC(e)}</span>
|
|
3208
3210
|
</summary>
|
|
3209
3211
|
${a?this.renderMessageGroupBody(e,t,r):null}
|
|
@@ -3225,7 +3227,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3225
3227
|
<span class=${i?`msg-meta expanded`:`msg-meta`} role="button" tabindex="0" title=${r} aria-label=${r} aria-expanded=${String(i)} @click=${()=>{this.expandedMetaKey=i?void 0:t}} @keydown=${e=>{this.onMetaKeydown(e,t,i)}}>${r}</span>
|
|
3226
3228
|
</div>
|
|
3227
3229
|
</div>
|
|
3228
|
-
`}renderMessageActions(e,t){let n=this.isCopyableMessage(e),r=
|
|
3230
|
+
`}renderMessageActions(e,t){let n=this.isCopyableMessage(e),r=LE(e,{enabled:this.canMessageActions,busy:this.messageActionsBusy()}),i=this.onEditFromHere===void 0?void 0:r.editFromHereEntryId,a=this.onForkFromHere===void 0?void 0:r.forkEntryId;if(!n&&i===void 0&&a===void 0)return null;let o=this.copiedMessageKey===t,s=a!==void 0&&this.forkingEntryId===a;return g`
|
|
3229
3231
|
<div class=${`msg-actions${s?` forking`:``}`} aria-label="Message actions">
|
|
3230
3232
|
${n?g`
|
|
3231
3233
|
<button type="button" class="msg-action" title=${o?`Copied`:`Copy message`} aria-label=${`${o?`Copied`:`Copy`} ${e.role} message`} @click=${n=>{this.copyMessage(e,t,n)}}>
|
|
@@ -3233,7 +3235,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3233
3235
|
</button>
|
|
3234
3236
|
`:null}
|
|
3235
3237
|
${i===void 0?null:g`
|
|
3236
|
-
<button type="button" class="msg-action msg-history-action" data-message-action="edit-from-here" title="Edit from here — branches within this session" @click=${()=>{this.editFromHere(i,
|
|
3238
|
+
<button type="button" class="msg-action msg-history-action" data-message-action="edit-from-here" title="Edit from here — branches within this session" @click=${()=>{this.editFromHere(i,RE(e))}}>
|
|
3237
3239
|
<svg class="msg-history-action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
3238
3240
|
<polyline points="15 10 20 15 15 20"></polyline>
|
|
3239
3241
|
<path d="M4 4v7a4 4 0 0 0 4 4h12"></path>
|
|
@@ -3255,7 +3257,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3255
3257
|
</div>
|
|
3256
3258
|
`}messageActionsBusy(){return this.isSendingPrompt||this.isCompacting||this.status?.isStreaming===!0||this.status?.isBashRunning===!0||this.status?.isCompacting===!0||(this.status?.pendingMessageCount??this.pendingMessageCount)>0}async editFromHere(e,t){await this.onEditFromHere?.(e,t)}async forkFromHere(e){if(this.forkingEntryId===void 0){this.forkingEntryId=e;try{await this.onForkFromHere?.(e)}finally{this.forkingEntryId===e&&(this.forkingEntryId=void 0)}}}onMetaKeydown(e,t,n){e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),this.expandedMetaKey=n?void 0:t)}isCopyableMessage(e){return(e.role===`user`||e.role===`assistant`)&&this.messageCopyText(e)!==``}messageCopyText(e){let t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;let n=e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(e=>e!==``).join(`
|
|
3257
3259
|
|
|
3258
|
-
`);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await uC(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}messageMetaLabel(e){let t=this.messageMetaCache.get(e);if(t!==void 0)return t;let n=
|
|
3260
|
+
`);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await uC(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}messageMetaLabel(e){let t=this.messageMetaCache.get(e);if(t!==void 0)return t;let n=IE(e);return this.messageMetaCache.set(e,n),n}renderPart(e,t,n=!1){if(e.type===`text`&&t?.role===`bash`)return g`<pre class="part shell-output">${e.text}</pre>`;if(e.type===`text`)return g`<formatted-text class="part" .text=${e.text} .live=${n}></formatted-text>`;if(e.type===`thinking`)return g`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text} .live=${n}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
|
|
3259
3261
|
<details class="part skill-invocation">
|
|
3260
3262
|
<summary><b>[skill]</b> ${e.name}</summary>
|
|
3261
3263
|
<small>${e.location}</small>
|
|
@@ -3266,60 +3268,60 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3266
3268
|
<strong>Loaded ${e.name}</strong>
|
|
3267
3269
|
<small>read ${e.path}</small>
|
|
3268
3270
|
</div>
|
|
3269
|
-
`;if(e.type===`image`){let{src:t,alt:n}=
|
|
3271
|
+
`;if(e.type===`image`){let{src:t,alt:n}=SE(e);return g`<img class="part chat-image" src=${t} alt=${n} loading="lazy" role="button" tabindex="0" title="Click to enlarge" @load=${this.onImageLoad} @click=${()=>{this.openImageZoom(t,n)}} @keydown=${e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.openImageZoom(t,n))}} />`}return e.type===`toolCall`?g`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type===`toolExecution`?g`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type===`toolResult`?g`
|
|
3270
3272
|
<details class="part" ?open=${e.isError}>
|
|
3271
3273
|
<summary>${e.isError?`✖`:`✓`} ${e.toolName} result</summary>
|
|
3272
3274
|
<formatted-text .text=${e.text} .live=${n}></formatted-text>
|
|
3273
3275
|
</details>
|
|
3274
|
-
`:null}onGroupToggle(e,t,n){let r=t.currentTarget;r instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,r.open,n)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleMinimapViewportUpdate(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){let t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){let e=this.chat;if(!e)return;let t=this.didChatHeightChange(),n=this.pinnedToBottom,r=e.scrollTop<this.lastScrollTop;if(t&&n){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:r?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){let e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){let t=e.get(`messageStart`);return typeof t==`number`&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;let e=this.chat;e&&EC({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){let e=this.chat;return!e||BC(e)}isAtBottom(){let e=this.chat;return!e||zC(e)<2}canScrollUp(){let e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;let e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{let t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){let e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{let n=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,n)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!==`missing`){this.updatePinnedToBottomAfterRestore(t.status),(t.status===`restored`||t.status===`bottom`)&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;let n=this.chat;n===void 0||!this.hasMore||this.loadingMore||(n.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore}updatePinnedToBottomAfterRestore(e){e===`bottom`?this.pinnedToBottom=!0:e===`restored`&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){let e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){let e=this.chat;if(e)return vC(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;let t=this.prependRestoreToken+1;this.prependRestoreToken=t;let n=0,r=()=>{let i=this.chat;if(!(!i||t!==this.prependRestoreToken)){if(yC(i,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=i.scrollTop,n+=1,n<30){requestAnimationFrame(r);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};r()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){let e=this.sessionId;this.scrollController.scheduleSave(e,e=>{this.sessionId===e&&this.saveScrollPosition(e)})}scheduleMinimapViewportUpdate(){this.minimapViewportFrame===void 0&&(this.minimapViewportFrame=requestAnimationFrame(()=>{this.minimapViewportFrame=void 0,this._updateMinimapViewport()}))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(`.scroll-marker`))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll(`[data-scroll-anchor-id]`))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,n){return n?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return CE(e)}groupRenderKey(e){return wE(e)}groupAnchorKey(e){return wE(e)}eventAnchorKey(e){return TE(e)}messageScrollMarkerId(e){return CE(e)}groupScrollMarkerId(e){return EE(e)}_updateMinimapViewport(){let e=this.chat;if(!e)return;let t=GC({scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,scrollTop:e.scrollTop});this._minimapLoadedPercent=this.hasMore?vE(this.messages.length/this.conversationDisplayTotal()*100):100,!JC(this._minimapViewport,t)&&(this._minimapViewport=t,this._minimapVisible===t.visible?this._pushMinimapViewport():this._minimapVisible=t.visible)}_pushMinimapViewport(){let e=this._minimap;e!==void 0&&(e.scrollRatio=this._minimapViewport.scrollRatio,e.viewportRatio=this._minimapViewport.viewportRatio,e.visible=this._minimapViewport.visible,e.loadedPercent=this._minimapLoadedPercent)}_requestMinimapMeasure(){this._minimapMeasureTimer===void 0&&(this._minimapMeasureTimer=setTimeout(()=>{this._minimapMeasureTimer=void 0,this._measureMinimapMarkers(),this._updateMinimapViewport()},150))}_measureMinimapMarkers(){let e=this.chat;if(!e||!this.messages.length){this._minimapMarkers=[];return}let t=e.getBoundingClientRect(),n=e.scrollHeight;if(n<=0){this._minimapMarkers=[];return}let r=this.renderRoot.querySelectorAll(`article.msg.user, article.msg.assistant`),i=[];for(let a of r){let r=a.dataset.index;if(r===void 0)continue;let o=Number(r);if(!Number.isFinite(o))continue;let s=o-this.messageStart;if(s<0||s>=this.messages.length)continue;let c=this.messages[s];if(c===void 0)continue;let l=this._minimapMessagePreview(c);if(!l)continue;let u=XC(a.getBoundingClientRect().top,t.top,e.scrollTop,n);if(c.role!==`user`&&c.role!==`assistant`)continue;let d=c.role;i.push({topRatio:u,role:d,preview:l})}this._minimapMarkers=i}_minimapMessagePreview(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(e=>e!==``).join(` `).slice(0,200)}_onMinimapScrollTo(e){let t=ew(e.detail);if(t===void 0)return;let n=this.chat;if(!n)return;let r=n.scrollHeight-n.clientHeight;r<=0||(n.scrollTop=KC(t/(1-this._minimapViewport.viewportRatio))*r,this.pinnedToBottom=BC(n))}static{this.styles=e_}};B([x({attribute:!1})],K.prototype,`messages`,void 0),B([x()],K.prototype,`sessionId`,void 0),B([x({type:Number})],K.prototype,`messageStart`,void 0),B([x({type:Number})],K.prototype,`messageEnd`,void 0),B([x({type:Number})],K.prototype,`messageTotal`,void 0),B([x({type:Boolean})],K.prototype,`hasMore`,void 0),B([x({type:Boolean})],K.prototype,`loadingMore`,void 0),B([x({type:Boolean})],K.prototype,`isSendingPrompt`,void 0),B([x({type:Boolean})],K.prototype,`isCompacting`,void 0),B([x({type:Number})],K.prototype,`pendingMessageCount`,void 0),B([x({attribute:!1})],K.prototype,`clientQueuedMessages`,void 0),B([x({attribute:!1})],K.prototype,`status`,void 0),B([x({type:Number})],K.prototype,`warningCount`,void 0),B([x({type:Boolean})],K.prototype,`warningsExpanded`,void 0),B([x({attribute:!1})],K.prototype,`onToggleWarnings`,void 0),B([x({attribute:!1})],K.prototype,`activity`,void 0),B([x({attribute:!1})],K.prototype,`sessionInfo`,void 0),B([x({attribute:!1})],K.prototype,`notificationInbox`,void 0),B([x({type:Boolean})],K.prototype,`canClearServerQueue`,void 0),B([x({type:Boolean})],K.prototype,`canMessageActions`,void 0),B([x({attribute:!1})],K.prototype,`onEditFromHere`,void 0),B([x({attribute:!1})],K.prototype,`onForkFromHere`,void 0),B([x({attribute:!1})],K.prototype,`onClearServerQueue`,void 0),B([x({attribute:!1})],K.prototype,`onDismissWarning`,void 0),B([x({attribute:!1})],K.prototype,`onDismissNotification`,void 0),B([x({attribute:!1})],K.prototype,`onDismissAllNotifications`,void 0),B([x({type:Boolean})],K.prototype,`warningsVisible`,void 0),B([x({attribute:!1})],K.prototype,`onLoadMore`,void 0),B([C(`.chat`)],K.prototype,`chat`,void 0),B([C(`chat-minimap`)],K.prototype,`_minimap`,void 0),B([C(`dialog.image-zoom`)],K.prototype,`imageZoomDialog`,void 0),B([S()],K.prototype,`pinnedToBottom`,void 0),B([S()],K.prototype,`zoomedImage`,void 0),B([S()],K.prototype,`expandedMetaKey`,void 0),B([S()],K.prototype,`copiedMessageKey`,void 0),B([S()],K.prototype,`forkingEntryId`,void 0),B([S()],K.prototype,`collapsedNotificationTargetKeys`,void 0),B([S()],K.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),B([S()],K.prototype,`loadMoreRequested`,void 0),B([S()],K.prototype,`sessionInfoOpen`,void 0),B([S()],K.prototype,`_minimapMarkers`,void 0),B([S()],K.prototype,`_minimapVisible`,void 0),K=B([b(`chat-view`)],K);var BE=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function VE(e){return typeof e==`string`&&BE.has(e)}function HE(e){switch(e){case`image/jpeg`:return`jpg`;case`image/png`:return`png`;case`image/gif`:return`gif`;case`image/webp`:return`webp`;default:return`bin`}}var UE=`application/octet-stream`,WE=`Failed to read an attachment.`;async function GE(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(YE(i,e))}catch{r=WE}return{attachments:n,...r===void 0?{}:{error:r}}}function KE(e){return e.kind===`image`&&VE(e.mimeType)}function qE(e){return e.every(e=>KE(e))}function JE(e,t){return qE(t)?e:`folder`}function YE(e,t){return VE(e.type)?{kind:`image`,name:ZE(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:ZE(e),mimeType:XE(e),data:t,size:e.size}}function XE(e){let t=e.type.trim();return t===``?UE:t}function ZE(e){return e.name===``?VE(e.type)?`pasted-image.${HE(e.type)}`:`pasted-file.bin`:e.name}var QE=`pi-webui:attachment-delivery`;function $E(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function eD(e=$E()){try{return e?.getItem(QE)===`folder`?`folder`:`inline`}catch{return`inline`}}function tD(e,t=$E()){try{t?.setItem(QE,e)}catch{}}var nD=`(pointer: coarse), (max-width: 760px)`,rD=`pi-webui.promptEnterPreference`;function iD(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(nD):void 0}function aD(e){return e===`send`||e===`newline`?e:`auto`}function oD(e=dD()){if(e===void 0)return`auto`;try{return aD(e.getItem(rD))}catch{return`auto`}}function sD(e,t=dD()){if(t!==void 0)try{t.setItem(rD,e)}catch{}}function cD(e=iD(),t=oD()){return t===`send`||t!==`newline`&&e?.matches!==!0}function lD(e,t,n=iD()){return e?n?.matches!==!0||t:!1}function uD(e,t=iD(),n=oD()){let r=cD(t,n);return e?!r:r}function dD(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function fD(){return _`
|
|
3276
|
+
`:null}onGroupToggle(e,t,n){let r=t.currentTarget;r instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,r.open,n)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleMinimapViewportUpdate(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){let t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){let e=this.chat;if(!e)return;let t=this.didChatHeightChange(),n=this.pinnedToBottom,r=e.scrollTop<this.lastScrollTop;if(t&&n){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:r?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){let e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){let t=e.get(`messageStart`);return typeof t==`number`&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;let e=this.chat;e&&EC({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){let e=this.chat;return!e||BC(e)}isAtBottom(){let e=this.chat;return!e||zC(e)<2}canScrollUp(){let e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;let e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{let t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){let e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{let n=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,n)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!==`missing`){this.updatePinnedToBottomAfterRestore(t.status),(t.status===`restored`||t.status===`bottom`)&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;let n=this.chat;n===void 0||!this.hasMore||this.loadingMore||(n.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore}updatePinnedToBottomAfterRestore(e){e===`bottom`?this.pinnedToBottom=!0:e===`restored`&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){let e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){let e=this.chat;if(e)return vC(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;let t=this.prependRestoreToken+1;this.prependRestoreToken=t;let n=0,r=()=>{let i=this.chat;if(!(!i||t!==this.prependRestoreToken)){if(yC(i,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=i.scrollTop,n+=1,n<30){requestAnimationFrame(r);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};r()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){let e=this.sessionId;this.scrollController.scheduleSave(e,e=>{this.sessionId===e&&this.saveScrollPosition(e)})}scheduleMinimapViewportUpdate(){this.minimapViewportFrame===void 0&&(this.minimapViewportFrame=requestAnimationFrame(()=>{this.minimapViewportFrame=void 0,this._updateMinimapViewport()}))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(`.scroll-marker`))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll(`[data-scroll-anchor-id]`))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,n){return n?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return wE(e)}groupRenderKey(e){return TE(e)}groupAnchorKey(e){return TE(e)}eventAnchorKey(e){return EE(e)}messageScrollMarkerId(e){return wE(e)}groupScrollMarkerId(e){return DE(e)}_updateMinimapViewport(){let e=this.chat;if(!e)return;let t=GC({scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,scrollTop:e.scrollTop});this._minimapLoadedPercent=this.hasMore?yE(this.messages.length/this.conversationDisplayTotal()*100):100,!JC(this._minimapViewport,t)&&(this._minimapViewport=t,this._minimapVisible===t.visible?this._pushMinimapViewport():this._minimapVisible=t.visible)}_pushMinimapViewport(){let e=this._minimap;e!==void 0&&(e.scrollRatio=this._minimapViewport.scrollRatio,e.viewportRatio=this._minimapViewport.viewportRatio,e.visible=this._minimapViewport.visible,e.loadedPercent=this._minimapLoadedPercent)}_requestMinimapMeasure(){this._minimapMeasureTimer===void 0&&(this._minimapMeasureTimer=setTimeout(()=>{this._minimapMeasureTimer=void 0,this._measureMinimapMarkers(),this._updateMinimapViewport()},150))}_measureMinimapMarkers(){let e=this.chat;if(!e||!this.messages.length){this._minimapMarkers=[];return}let t=e.getBoundingClientRect(),n=e.scrollHeight;if(n<=0){this._minimapMarkers=[];return}let r=this.renderRoot.querySelectorAll(`article.msg.user, article.msg.assistant`),i=[];for(let a of r){let r=a.dataset.index;if(r===void 0)continue;let o=Number(r);if(!Number.isFinite(o))continue;let s=o-this.messageStart;if(s<0||s>=this.messages.length)continue;let c=this.messages[s];if(c===void 0)continue;let l=this._minimapMessagePreview(c);if(!l)continue;let u=XC(a.getBoundingClientRect().top,t.top,e.scrollTop,n);if(c.role!==`user`&&c.role!==`assistant`)continue;let d=c.role;i.push({topRatio:u,role:d,preview:l})}this._minimapMarkers=i}_minimapMessagePreview(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(e=>e!==``).join(` `).slice(0,200)}_onMinimapScrollTo(e){let t=ew(e.detail);if(t===void 0)return;let n=this.chat;if(!n)return;let r=n.scrollHeight-n.clientHeight;r<=0||(n.scrollTop=KC(t/(1-this._minimapViewport.viewportRatio))*r,this.pinnedToBottom=BC(n))}static{this.styles=e_}};B([x({attribute:!1})],K.prototype,`messages`,void 0),B([x()],K.prototype,`sessionId`,void 0),B([x({type:Number})],K.prototype,`messageStart`,void 0),B([x({type:Number})],K.prototype,`messageEnd`,void 0),B([x({type:Number})],K.prototype,`messageTotal`,void 0),B([x({type:Boolean})],K.prototype,`hasMore`,void 0),B([x({type:Boolean})],K.prototype,`loadingMore`,void 0),B([x({type:Boolean})],K.prototype,`isSendingPrompt`,void 0),B([x({type:Boolean})],K.prototype,`isCompacting`,void 0),B([x({type:Number})],K.prototype,`pendingMessageCount`,void 0),B([x({attribute:!1})],K.prototype,`clientQueuedMessages`,void 0),B([x({attribute:!1})],K.prototype,`status`,void 0),B([x({type:Number})],K.prototype,`warningCount`,void 0),B([x({type:Boolean})],K.prototype,`warningsExpanded`,void 0),B([x({attribute:!1})],K.prototype,`onToggleWarnings`,void 0),B([x({attribute:!1})],K.prototype,`activity`,void 0),B([x({attribute:!1})],K.prototype,`sessionInfo`,void 0),B([x({attribute:!1})],K.prototype,`notificationInbox`,void 0),B([x({type:Boolean})],K.prototype,`canClearServerQueue`,void 0),B([x({type:Boolean})],K.prototype,`canMessageActions`,void 0),B([x({attribute:!1})],K.prototype,`onEditFromHere`,void 0),B([x({attribute:!1})],K.prototype,`onForkFromHere`,void 0),B([x({attribute:!1})],K.prototype,`onClearServerQueue`,void 0),B([x({attribute:!1})],K.prototype,`onDismissWarning`,void 0),B([x({attribute:!1})],K.prototype,`onDismissNotification`,void 0),B([x({attribute:!1})],K.prototype,`onDismissAllNotifications`,void 0),B([x({type:Boolean})],K.prototype,`warningsVisible`,void 0),B([x({attribute:!1})],K.prototype,`onLoadMore`,void 0),B([C(`.chat`)],K.prototype,`chat`,void 0),B([C(`chat-minimap`)],K.prototype,`_minimap`,void 0),B([C(`dialog.image-zoom`)],K.prototype,`imageZoomDialog`,void 0),B([S()],K.prototype,`pinnedToBottom`,void 0),B([S()],K.prototype,`zoomedImage`,void 0),B([S()],K.prototype,`expandedMetaKey`,void 0),B([S()],K.prototype,`copiedMessageKey`,void 0),B([S()],K.prototype,`forkingEntryId`,void 0),B([S()],K.prototype,`collapsedNotificationTargetKeys`,void 0),B([S()],K.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),B([S()],K.prototype,`loadMoreRequested`,void 0),B([S()],K.prototype,`sessionInfoOpen`,void 0),B([S()],K.prototype,`_minimapMarkers`,void 0),B([S()],K.prototype,`_minimapVisible`,void 0),K=B([b(`chat-view`)],K);var VE=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function HE(e){return typeof e==`string`&&VE.has(e)}function UE(e){switch(e){case`image/jpeg`:return`jpg`;case`image/png`:return`png`;case`image/gif`:return`gif`;case`image/webp`:return`webp`;default:return`bin`}}var WE=`application/octet-stream`,GE=`Failed to read an attachment.`;async function KE(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(XE(i,e))}catch{r=GE}return{attachments:n,...r===void 0?{}:{error:r}}}function qE(e){return e.kind===`image`&&HE(e.mimeType)}function JE(e){return e.every(e=>qE(e))}function YE(e,t){return JE(t)?e:`folder`}function XE(e,t){return HE(e.type)?{kind:`image`,name:QE(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:QE(e),mimeType:ZE(e),data:t,size:e.size}}function ZE(e){let t=e.type.trim();return t===``?WE:t}function QE(e){return e.name===``?HE(e.type)?`pasted-image.${UE(e.type)}`:`pasted-file.bin`:e.name}var $E=`pi-webui:attachment-delivery`;function eD(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function tD(e=eD()){try{return e?.getItem($E)===`folder`?`folder`:`inline`}catch{return`inline`}}function nD(e,t=eD()){try{t?.setItem($E,e)}catch{}}var rD=`(pointer: coarse), (max-width: 760px)`,iD=`pi-webui.promptEnterPreference`;function aD(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(rD):void 0}function oD(e){return e===`send`||e===`newline`?e:`auto`}function sD(e=fD()){if(e===void 0)return`auto`;try{return oD(e.getItem(iD))}catch{return`auto`}}function cD(e,t=fD()){if(t!==void 0)try{t.setItem(iD,e)}catch{}}function lD(e=aD(),t=sD()){return t===`send`||t!==`newline`&&e?.matches!==!0}function uD(e,t,n=aD()){return e?n?.matches!==!0||t:!1}function dD(e,t=aD(),n=sD()){let r=lD(t,n);return e?!r:r}function fD(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function pD(){return _`
|
|
3275
3277
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3276
3278
|
<path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
|
|
3277
3279
|
</svg>
|
|
3278
|
-
`}function
|
|
3280
|
+
`}function mD(){return _`
|
|
3279
3281
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3280
3282
|
<polyline points="4 14 10 14 10 20"></polyline>
|
|
3281
3283
|
<polyline points="20 10 14 10 14 4"></polyline>
|
|
3282
3284
|
<line x1="10" y1="14" x2="3" y2="21"></line>
|
|
3283
3285
|
<line x1="21" y1="3" x2="14" y2="10"></line>
|
|
3284
3286
|
</svg>
|
|
3285
|
-
`}function
|
|
3287
|
+
`}function hD(){return _`
|
|
3286
3288
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3287
3289
|
<path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
|
|
3288
3290
|
<path d="M21 3 11.5 12.5"></path>
|
|
3289
3291
|
</svg>
|
|
3290
|
-
`}function
|
|
3292
|
+
`}function gD(){return _`
|
|
3291
3293
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3292
3294
|
<path d="M4 7h11"></path>
|
|
3293
3295
|
<path d="M4 12h7"></path>
|
|
3294
3296
|
<path d="M4 17h7"></path>
|
|
3295
3297
|
<path d="m15 14 5 3-5 3z"></path>
|
|
3296
3298
|
</svg>
|
|
3297
|
-
`}function
|
|
3299
|
+
`}function _D(){return hD()}function vD(){return _`
|
|
3298
3300
|
<svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3299
3301
|
<rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
|
|
3300
3302
|
</svg>
|
|
3301
|
-
`}function
|
|
3303
|
+
`}function yD(e){let t=Math.max(e.total,1),n=t>1?1.4:0,r=(18-n*(t-1))/t,i=Math.min(r,5),a=3+(18-(i*t+n*(t-1)))/2,o=Math.min(.75,i*.3);return _`
|
|
3302
3304
|
<svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3303
3305
|
${Array.from({length:t},(r,s)=>{let c=a+s*(i+n),l=5+(t===1?1:s/(t-1))*13,u=21-l;return _`<rect class=${s<e.filled?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${c} y=${u} width=${i} height=${l} rx=${o}></rect>`})}
|
|
3304
3306
|
</svg>
|
|
3305
|
-
`}var
|
|
3307
|
+
`}var bD=Hb(class extends Ub{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===Vb.ELEMENT}update(e,[t,n]){if(!this.isElementPart)throw Error(`scrollWhenSelected must be used on an element`);if(t&&(!this.wasSelected||n!==this.previousKey)){let t=`element`in e?e.element:void 0;requestAnimationFrame(()=>{t instanceof HTMLElement&&typeof t.scrollIntoView==`function`&&t.scrollIntoView({block:`nearest`})})}this.wasSelected=t,this.previousKey=n}render(e,t){}}),xD=class extends y{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
|
|
3306
3308
|
<div class="menu">
|
|
3307
3309
|
${this.items.map((e,t)=>g`
|
|
3308
|
-
<button class=${t===this.selectedIndex?`selected`:``} ${
|
|
3310
|
+
<button class=${t===this.selectedIndex?`selected`:``} ${bD(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
|
|
3309
3311
|
<strong>${e.insertText}</strong>
|
|
3310
3312
|
<span>${e.detail}</span>
|
|
3311
3313
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
3312
3314
|
</button>
|
|
3313
3315
|
`)}
|
|
3314
3316
|
</div>
|
|
3315
|
-
`:null}static{this.styles=n_}};B([x({attribute:!1})],
|
|
3317
|
+
`:null}static{this.styles=n_}};B([x({attribute:!1})],xD.prototype,`items`,void 0),B([x({type:Number})],xD.prototype,`selectedIndex`,void 0),B([x({attribute:!1})],xD.prototype,`onPick`,void 0),xD=B([b(`autocomplete-menu`)],xD);var SD=`Model tier ladder is invalid. Tiered mode stays unavailable until the ladder is fixed in Settings → Model tiers.`,CD=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.editable=!1,this.error=``,this.menuOpen=!1,this.menuStyle=``,this.onDocumentClick=e=>{!this.menuOpen||_b(e,this.renderRoot)||(this.menuOpen=!1)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}render(){let e=this.effectiveStatus();if(e===void 0)return v;let t=e.mode===`tiered`?`Tiered`:`Exact`,n=this.compactDiagnostic(e);return g`
|
|
3316
3318
|
<button
|
|
3317
3319
|
type="button"
|
|
3318
3320
|
class="policy-trigger action-menu"
|
|
3319
3321
|
aria-label=${`Session model mode: ${t}`}
|
|
3320
3322
|
aria-haspopup="menu"
|
|
3321
3323
|
aria-expanded=${String(this.menuOpen)}
|
|
3322
|
-
title=${
|
|
3324
|
+
title=${wD(e,t)}
|
|
3323
3325
|
@click=${e=>{this.toggleModeMenu(e.currentTarget)}}
|
|
3324
3326
|
>
|
|
3325
3327
|
<span class="policy-mode">${t}</span>
|
|
@@ -3349,7 +3351,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3349
3351
|
<span class="policy-mode-hint">${n}</span>
|
|
3350
3352
|
<span class="policy-mode-check" aria-hidden="true">${i?`✓`:v}</span>
|
|
3351
3353
|
</button>
|
|
3352
|
-
`}toggleModeMenu(e){if(!this.canMutate()){this.menuOpen=!1;return}if(this.menuOpen){this.menuOpen=!1;return}this.menuStyle=vb(e,{constrainTo:`viewport`}),this.menuOpen=!0}selectMode(e){if(!this.canMutate()){this.menuOpen=!1;return}this.menuOpen=!1,this.onSelectMode?.(e)}handleMenuKeydown(e){!this.menuOpen||e.key!==`Escape`||(e.preventDefault(),e.stopPropagation(),this.menuOpen=!1,this.updateComplete.then(()=>{this.isConnected&&this.renderRoot.querySelector(`.policy-trigger`)?.focus()}))}compactDiagnostic(e){let t=this.blockedReason();if(t!==void 0)return t;if(e.mode===`tiered`&&!e.ladderValid)return
|
|
3354
|
+
`}toggleModeMenu(e){if(!this.canMutate()){this.menuOpen=!1;return}if(this.menuOpen){this.menuOpen=!1;return}this.menuStyle=vb(e,{constrainTo:`viewport`}),this.menuOpen=!0}selectMode(e){if(!this.canMutate()){this.menuOpen=!1;return}this.menuOpen=!1,this.onSelectMode?.(e)}handleMenuKeydown(e){!this.menuOpen||e.key!==`Escape`||(e.preventDefault(),e.stopPropagation(),this.menuOpen=!1,this.updateComplete.then(()=>{this.isConnected&&this.renderRoot.querySelector(`.policy-trigger`)?.focus()}))}compactDiagnostic(e){let t=this.blockedReason();if(t!==void 0)return t;if(e.mode===`tiered`&&!e.ladderValid)return SD;let n=this.error.trim();return n===``?void 0:n}effectiveStatus(){return this.status}blockedReason(){let e=this.effectiveStatus()?.blockedReason;return e===void 0||e.trim()===``?void 0:e}canMutate(){return this.editable&&!this.loading&&!this.saving}static{this.styles=h`
|
|
3353
3355
|
:host { position: relative; min-width: 0; display: inline-flex; align-items: center; gap: 6px; font: inherit; }
|
|
3354
3356
|
* { box-sizing: border-box; }
|
|
3355
3357
|
.policy-trigger { flex: 1 1 auto; min-width: 0; max-width: 100%; overflow: hidden; display: inline-flex; align-items: baseline; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 9px; font: inherit; font-size: 12px; line-height: 1.3; cursor: pointer; }
|
|
@@ -3363,7 +3365,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3363
3365
|
.policy-mode-hint { min-width: 0; color: var(--pi-muted); font-size: 11px; line-height: 1.3; }
|
|
3364
3366
|
.policy-mode-check { grid-column: 2; grid-row: 1 / span 2; width: 18px; color: var(--pi-accent); font-weight: 700; text-align: center; }
|
|
3365
3367
|
.policy-diagnostic { min-width: 0; max-width: 22ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-danger); font-size: 11px; }
|
|
3366
|
-
`}};B([x({attribute:!1})],
|
|
3368
|
+
`}};B([x({attribute:!1})],CD.prototype,`status`,void 0),B([x({attribute:!1})],CD.prototype,`catalog`,void 0),B([x({type:Boolean})],CD.prototype,`loading`,void 0),B([x({type:Boolean})],CD.prototype,`saving`,void 0),B([x({type:Boolean})],CD.prototype,`editable`,void 0),B([x()],CD.prototype,`error`,void 0),B([x({attribute:!1})],CD.prototype,`onSelectMode`,void 0),B([S()],CD.prototype,`menuOpen`,void 0),B([S()],CD.prototype,`menuStyle`,void 0),CD=B([b(`session-model-policy-control`)],CD);function wD(e,t){let n=e.tier;return`Session model mode: ${t}${e.mode===`tiered`&&n!==void 0?` · ${Ic[n]}`:``} · ${zc(e.resolved)}`}var TD=class extends y{constructor(...e){super(...e),this.options=[],this.label=``,this.editable=!1,this.menuOpen=!1,this.menuStyle=``,this.onDocumentClick=e=>{!this.menuOpen||_b(e,this.renderRoot)||(this.menuOpen=!1)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}render(){return g`
|
|
3367
3369
|
<button
|
|
3368
3370
|
type="button"
|
|
3369
3371
|
class="thinking-trigger action-menu"
|
|
@@ -3373,7 +3375,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3373
3375
|
title=${this.label}
|
|
3374
3376
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
3375
3377
|
>
|
|
3376
|
-
<span class="thinking-trigger-gauge">${
|
|
3378
|
+
<span class="thinking-trigger-gauge">${yD(this.triggerGauge())}</span>
|
|
3377
3379
|
<span class="thinking-chevron" aria-hidden="true">▾</span>
|
|
3378
3380
|
</button>
|
|
3379
3381
|
${this.menuOpen?this.renderMenu():null}
|
|
@@ -3424,7 +3426,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3424
3426
|
.thinking-item-unsupported { cursor: not-allowed; opacity: 0.72; }
|
|
3425
3427
|
.thinking-item-unsupported:hover, .thinking-item-unsupported:focus-visible { background: transparent; }
|
|
3426
3428
|
.thinking-item-check { grid-column: 2; grid-row: 1 / span 3; width: 18px; color: var(--pi-accent); font-weight: 700; text-align: center; }
|
|
3427
|
-
`}};B([x({attribute:!1})],
|
|
3429
|
+
`}};B([x({attribute:!1})],TD.prototype,`options`,void 0),B([x()],TD.prototype,`label`,void 0),B([x({type:Boolean})],TD.prototype,`editable`,void 0),B([x({attribute:!1})],TD.prototype,`onSelectLevel`,void 0),B([S()],TD.prototype,`menuOpen`,void 0),B([S()],TD.prototype,`menuStyle`,void 0),TD=B([b(`session-thinking-menu`)],TD);var ED=class extends y{constructor(...e){super(...e),this.label=``,this.editable=!1,this.menuOpen=!1,this.menuStyle=``,this.onDocumentClick=e=>{!this.menuOpen||_b(e,this.renderRoot)||(this.menuOpen=!1)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}render(){let e=this.selectedTier===void 0?void 0:this.catalog?.ladder?.[this.selectedTier];return g`
|
|
3428
3430
|
<button
|
|
3429
3431
|
type="button"
|
|
3430
3432
|
class="tier-trigger action-menu"
|
|
@@ -3481,12 +3483,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3481
3483
|
.tier-item-invalid:hover, .tier-item-invalid:focus-visible { background: transparent; }
|
|
3482
3484
|
.tier-item-reason { color: var(--pi-danger); }
|
|
3483
3485
|
.tier-item-check { grid-column: 2; grid-row: 1 / span 2; width: 18px; color: var(--pi-accent); font-weight: 700; text-align: center; }
|
|
3484
|
-
`}};B([x({attribute:!1})],
|
|
3486
|
+
`}};B([x({attribute:!1})],ED.prototype,`catalog`,void 0),B([x()],ED.prototype,`selectedTier`,void 0),B([x()],ED.prototype,`label`,void 0),B([x({type:Boolean})],ED.prototype,`editable`,void 0),B([x({attribute:!1})],ED.prototype,`onSelectTier`,void 0),B([S()],ED.prototype,`menuOpen`,void 0),B([S()],ED.prototype,`menuStyle`,void 0),ED=B([b(`session-tier-menu`)],ED);var q=class extends y{constructor(...e){super(...e),this.disabled=!1,this.sendDisabled=!1,this.machineId=`local`,this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.showSessionConfiguration=!1,this.policyThinkingOptions=[],this.modelPolicyLoading=!1,this.modelPolicySaving=!1,this.modelPolicyError=``,this.availableThinkingLevels=[],this.attachmentDrafts=Qu,this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=tD(),this.attachmentError=void 0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=aD(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=AD(e.has(`machineId`)?e.get(`machineId`):this.machineId,t),r=this.attachmentScope??(n===void 0?void 0:this.attachmentDrafts.findScope(n));n!==void 0&&rd(n,this.draft);let i=AD(this.machineId,this.sessionId);n!==void 0&&n!==i&&r?.currentKey()===n&&(this.attachments.length>0||this.attachmentError!==void 0)&&r.write(this.currentAttachmentDraft()),this.draft=i===void 0?``:nd(i);let a=i===void 0?void 0:this.attachmentDrafts.openScope(i);this.attachmentScope=a,this.adoptAttachmentDraft(a?.read()??{attachments:[]}),this.currentInputMode=mf(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){if(e.has(`status`)&&[...e.keys()].every(e=>e===`status`||e===`modelPolicyStatus`)){let t=DD(e.get(`status`),this.status),n=!e.has(`modelPolicyStatus`)||OD(e.get(`modelPolicyStatus`),this.modelPolicyStatus);return!t||!n}return!0}firstUpdated(){this.createEditor()}updated(e){e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){let e=this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.disabled||this.sending,i=r||this.sendDisabled,a=r||this.canSteer||this.isCompacting||this.canStop;return g`
|
|
3485
3487
|
<footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
|
|
3486
3488
|
<div class="editor-wrap">
|
|
3487
3489
|
<div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="Message pi" aria-disabled=${this.disabled?`true`:`false`}></div>
|
|
3488
3490
|
<input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
|
|
3489
|
-
<button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${
|
|
3491
|
+
<button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${pD()}</button>
|
|
3490
3492
|
${t?g`<div class="mode-hint">Shell command${e.excludeFromContext?` · excluded from context`:``}</div>`:null}
|
|
3491
3493
|
${this.isCompacting&&!t?g`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
|
|
3492
3494
|
${this.renderAttachments()}
|
|
@@ -3494,13 +3496,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3494
3496
|
</div>
|
|
3495
3497
|
<div class="actions">
|
|
3496
3498
|
${this.renderCompactStatus()}
|
|
3497
|
-
${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${a} title="Compact context" aria-label="Compact context" @click=${()=>this.onCompact?.()}>${
|
|
3498
|
-
<button class="icon-button send-button" ?disabled=${i} title=${n?`Queue until the current activity finishes`:`Send message`} aria-label=${n?`Queue message`:`Send message`} @click=${()=>{this.send(`followUp`)}}>${n?
|
|
3499
|
-
${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${i} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send(`steer`)}}>${
|
|
3500
|
-
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`Stop current work and clear queued messages`:`Nothing running`} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${
|
|
3499
|
+
${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${a} title="Compact context" aria-label="Compact context" @click=${()=>this.onCompact?.()}>${mD()}<span>Compact</span></button>`}
|
|
3500
|
+
<button class="icon-button send-button" ?disabled=${i} title=${n?`Queue until the current activity finishes`:`Send message`} aria-label=${n?`Queue message`:`Send message`} @click=${()=>{this.send(`followUp`)}}>${n?gD():hD()}</button>
|
|
3501
|
+
${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${i} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send(`steer`)}}>${_D()}</button>`:null}
|
|
3502
|
+
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`Stop current work and clear queued messages`:`Nothing running`} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${vD()}</button>
|
|
3501
3503
|
</div>
|
|
3502
3504
|
</footer>
|
|
3503
|
-
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=
|
|
3505
|
+
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=AD(this.machineId,this.sessionId);t!==void 0&&rd(t,e);let n=this.editor;if(n!==void 0){let t=n.state.doc.toString();n.dispatch({...t===e?{}:{changes:{from:0,to:t.length,insert:e}},selection:i.cursor(e.length)})}this.requestVersion+=1,this.currentInputMode=mf(e),this.completions=[],this.selectedIndex=0}get view(){return this.editor}renderCompactStatus(){let e=this.status===void 0&&this.showSessionConfiguration,t=this.status??(e?this.sessionConfiguration:void 0);if(t===void 0&&!e)return null;let n=this.modelPolicyStatus??this.status?.modelPolicy,r=t?.model?.id??(e?`Choose default model`:`no model`),i=t?.model?.provider!==void 0&&t.model.provider!==``?`${t.model.provider}/`:``,a=e?`Default thinking level: ${Zt(t?.thinkingLevel)}`:`Thinking level: ${Zt(t?.thinkingLevel)}`,o=!this.disabled&&!this.modelPolicySaving&&!kD(this.status);return g`
|
|
3504
3506
|
<div class="compact-status" aria-label=${e?`Session defaults`:`Session status`}>
|
|
3505
3507
|
${n===void 0?null:g`
|
|
3506
3508
|
<session-model-policy-control
|
|
@@ -3524,7 +3526,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3524
3526
|
`:g`
|
|
3525
3527
|
<button class="select-model" ?disabled=${this.onSelectModel===void 0} title="Select model" @click=${()=>this.onSelectModel?.()}>${i}${r}</button>
|
|
3526
3528
|
${n===void 0?g`
|
|
3527
|
-
<button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0} title=${a} aria-label=${a} @click=${()=>this.onSelectThinking?.()}>${
|
|
3529
|
+
<button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0} title=${a} aria-label=${a} @click=${()=>this.onSelectThinking?.()}>${yD(Qt(t?.thinkingLevel,this.availableThinkingLevels))}</button>
|
|
3528
3530
|
`:g`
|
|
3529
3531
|
<session-thinking-menu
|
|
3530
3532
|
.options=${this.policyThinkingOptions}
|
|
@@ -3535,10 +3537,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3535
3537
|
`}
|
|
3536
3538
|
`}
|
|
3537
3539
|
</div>
|
|
3538
|
-
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=
|
|
3540
|
+
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=JE(this.attachments),t=this.effectiveAttachmentDelivery();return g`
|
|
3539
3541
|
<div class="attachments" aria-label="Pending attachments">
|
|
3540
3542
|
${this.attachments.map(e=>g`
|
|
3541
|
-
<div class=${`attachment-chip ${
|
|
3543
|
+
<div class=${`attachment-chip ${qE(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
|
|
3542
3544
|
${this.renderAttachmentPreview(e)}
|
|
3543
3545
|
<button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
|
|
3544
3546
|
</div>
|
|
@@ -3553,10 +3555,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3553
3555
|
`:null}
|
|
3554
3556
|
${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
|
|
3555
3557
|
</div>
|
|
3556
|
-
`}renderAttachmentPreview(e){return
|
|
3557
|
-
<div class="attachment-file-preview" aria-hidden="true">${
|
|
3558
|
+
`}renderAttachmentPreview(e){return qE(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
|
|
3559
|
+
<div class="attachment-file-preview" aria-hidden="true">${ID(e.name)}</div>
|
|
3558
3560
|
<span class="attachment-file-name">${e.name}</span>
|
|
3559
|
-
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!qE(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,tD(this.attachmentDelivery)}attachmentScopeKey(){return kD(this.machineId,this.sessionId)}activeAttachmentScope(){let e=this.attachmentScopeKey();if(e!==void 0)return this.attachmentScope?.currentKey()===void 0&&(this.attachmentScope=this.attachmentDrafts.openScope(e)),this.attachmentScope}currentAttachmentDraft(){return{attachments:this.attachments,...this.attachmentError===void 0?{}:{error:this.attachmentError}}}adoptAttachmentDraft(e){this.attachments=[...e.attachments],this.attachmentError=e.error}persistAttachmentDraft(){let e=this.activeAttachmentScope();e!==void 0&&e.write(this.currentAttachmentDraft())}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e),this.persistAttachmentDraft()}async handlePaste(e){let t=MD(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&ND(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=MD(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){let t=this.activeAttachmentScope();if(t===void 0){this.attachmentError=void 0;let t=await GE(e,ID);t.attachments.length>0&&(this.attachments=[...this.attachments,...t.attachments.map(e=>({id:this.attachmentDrafts.nextAttachmentId(),...e}))]),this.attachmentError=t.error;return}this.attachmentError=void 0;let n=t.beginCapture(),{attachments:r,error:i}=await GE(e,ID),a=n.complete(r,i);a!==void 0&&t.currentKey()===this.attachmentScopeKey()&&this.adoptAttachmentDraft(a)}currentAttachments(){return this.attachments.map(e=>PD(e))}effectiveAttachmentDelivery(){return JE(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new p({parent:this.editorHost,state:e.create({doc:this.draft,extensions:[m(),ne(),t(),u.of(` `),r(a,{fallback:!0}),p.lineWrapping,p.contentAttributes.of(e=>zD(e.state.sliceDoc(0,e.state.selection.main.head))),p.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),o(`Message pi... Use / for commands, @ for tracked files, @ space for all files`),this.editableCompartment.of(p.editable.of(!this.disabled)),this.readOnlyCompartment.of(e.readOnly.of(this.disabled)),p.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),n.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>l.shift?.(e)??!1},{key:`Backspace`,run:e=>ee(e)},...c,...d])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:i.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(p.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(e.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=kD(this.machineId,this.sessionId);t!==void 0&&rd(t,this.draft);let n=mf(this.draft);gf(n,this.currentInputMode)||(this.currentInputMode=n),this.refreshCompletions()}async refreshCompletions(){let e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await Cs.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(AD);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:t.source,...t.description===void 0?{}:{description:t.description}}))}else if(e.kind===`file`&&this.cwd!==void 0&&this.cwd!==``){let n=await Cs.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(jD);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=lf(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}}currentTrigger(){return cf(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=lD(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,n)}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return uD(t,this.mobilePromptEnterMedia,oD())?(this.send(this.canSteer||this.isCompacting?`followUp`:void 0),!0):te(e)||f(e)}handleEditorTab(e){if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):l.run?.(e)??!1}pick(e){let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,a=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:a,insert:`${e.insertText}${n}`},selection:i.cursor(r),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending||this.sendDisabled)return;let t=this.draft.trim(),n=this.attachments;if(t===``&&n.length===0)return;let r=this.canSteer||this.isCompacting?e:void 0,i=n.length>0?this.currentAttachments():void 0,a=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=kD(this.machineId,this.sessionId);e!==void 0&&id(e);let t=e===void 0?void 0:this.activeAttachmentScope();t!==void 0&&t.clear(),this.attachmentScope=void 0,this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=a_}};B([x({type:Boolean})],q.prototype,`disabled`,void 0),B([x({type:Boolean})],q.prototype,`sendDisabled`,void 0),B([x()],q.prototype,`sessionId`,void 0),B([x()],q.prototype,`cwd`,void 0),B([x()],q.prototype,`machineId`,void 0),B([x()],q.prototype,`projectId`,void 0),B([x()],q.prototype,`workspaceId`,void 0),B([x({type:Boolean})],q.prototype,`workspaceScopedFileSuggestions`,void 0),B([x({type:Boolean})],q.prototype,`canSteer`,void 0),B([x({type:Boolean})],q.prototype,`isCompacting`,void 0),B([x({type:Boolean})],q.prototype,`canStop`,void 0),B([x({attribute:!1})],q.prototype,`status`,void 0),B([x({type:Boolean})],q.prototype,`sending`,void 0),B([x({attribute:!1})],q.prototype,`onSend`,void 0),B([x({attribute:!1})],q.prototype,`onStop`,void 0),B([x({attribute:!1})],q.prototype,`onSelectModel`,void 0),B([x({attribute:!1})],q.prototype,`onSelectThinking`,void 0),B([x({attribute:!1})],q.prototype,`onCompact`,void 0),B([x({type:Boolean})],q.prototype,`showSessionConfiguration`,void 0),B([x({attribute:!1})],q.prototype,`sessionConfiguration`,void 0),B([x({attribute:!1})],q.prototype,`modelPolicyStatus`,void 0),B([x({attribute:!1})],q.prototype,`modelTierCatalog`,void 0),B([x({attribute:!1})],q.prototype,`onSelectPolicyMode`,void 0),B([x({attribute:!1})],q.prototype,`onSelectPolicyTier`,void 0),B([x({attribute:!1})],q.prototype,`onSelectPolicyThinking`,void 0),B([x({attribute:!1})],q.prototype,`policyThinkingOptions`,void 0),B([x({type:Boolean})],q.prototype,`modelPolicyLoading`,void 0),B([x({type:Boolean})],q.prototype,`modelPolicySaving`,void 0),B([x()],q.prototype,`modelPolicyError`,void 0),B([x({attribute:!1})],q.prototype,`availableThinkingLevels`,void 0),B([x({attribute:!1})],q.prototype,`attachmentDrafts`,void 0),B([C(`.markdown-editor`)],q.prototype,`editorHost`,void 0),B([C(`.attachment-input`)],q.prototype,`attachmentInput`,void 0),B([S()],q.prototype,`currentInputMode`,void 0),B([S()],q.prototype,`completions`,void 0),B([S()],q.prototype,`selectedIndex`,void 0),B([S()],q.prototype,`attachments`,void 0),B([S()],q.prototype,`attachmentDelivery`,void 0),B([S()],q.prototype,`attachmentError`,void 0),q=B([b(`prompt-editor`)],q);function ED(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel&&DD(e.modelPolicy,t.modelPolicy)&&OD(e)===OD(t)}function DD(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.mode===t.mode&&e.tier===t.tier&&e.resolved.model.provider===t.resolved.model.provider&&e.resolved.model.id===t.resolved.model.id&&e.resolved.thinkingLevel===t.resolved.thinkingLevel&&e.ladderValid===t.ladderValid&&e.blockedReason===t.blockedReason}function OD(e){return e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function kD(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return qc(e,t)}function AD(){return[]}function jD(){return[]}function MD(e){return e===null?[]:Array.from(e.files)}function ND(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function PD(e){return e.kind===`image`?{kind:`image`,mimeType:e.mimeType,data:e.data,name:e.name}:{kind:`file`,mimeType:e.mimeType,data:e.data,name:e.name}}function FD(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function ID(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(`Failed to read file`))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(`Unexpected file reader result`));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var LD={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},RD={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function zD(e){return mf(e).kind===`normal`?LD:RD}var BD=class extends y{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
|
|
3561
|
+
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!JE(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,nD(this.attachmentDelivery)}attachmentScopeKey(){return AD(this.machineId,this.sessionId)}activeAttachmentScope(){let e=this.attachmentScopeKey();if(e!==void 0)return this.attachmentScope?.currentKey()===void 0&&(this.attachmentScope=this.attachmentDrafts.openScope(e)),this.attachmentScope}currentAttachmentDraft(){return{attachments:this.attachments,...this.attachmentError===void 0?{}:{error:this.attachmentError}}}adoptAttachmentDraft(e){this.attachments=[...e.attachments],this.attachmentError=e.error}persistAttachmentDraft(){let e=this.activeAttachmentScope();e!==void 0&&e.write(this.currentAttachmentDraft())}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e),this.persistAttachmentDraft()}async handlePaste(e){let t=ND(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&PD(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=ND(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){let t=this.activeAttachmentScope();if(t===void 0){this.attachmentError=void 0;let t=await KE(e,LD);t.attachments.length>0&&(this.attachments=[...this.attachments,...t.attachments.map(e=>({id:this.attachmentDrafts.nextAttachmentId(),...e}))]),this.attachmentError=t.error;return}this.attachmentError=void 0;let n=t.beginCapture(),{attachments:r,error:i}=await KE(e,LD),a=n.complete(r,i);a!==void 0&&t.currentKey()===this.attachmentScopeKey()&&this.adoptAttachmentDraft(a)}currentAttachments(){return this.attachments.map(e=>FD(e))}effectiveAttachmentDelivery(){return YE(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new p({parent:this.editorHost,state:e.create({doc:this.draft,extensions:[m(),ne(),t(),u.of(` `),r(a,{fallback:!0}),p.lineWrapping,p.contentAttributes.of(e=>BD(e.state.sliceDoc(0,e.state.selection.main.head))),p.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),o(`Message pi... Use / for commands, @ for tracked files, @ space for all files`),this.editableCompartment.of(p.editable.of(!this.disabled)),this.readOnlyCompartment.of(e.readOnly.of(this.disabled)),p.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),n.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>l.shift?.(e)??!1},{key:`Backspace`,run:e=>ee(e)},...c,...d])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:i.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(p.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(e.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=AD(this.machineId,this.sessionId);t!==void 0&&rd(t,this.draft);let n=mf(this.draft);gf(n,this.currentInputMode)||(this.currentInputMode=n),this.refreshCompletions()}async refreshCompletions(){let e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await Cs.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(jD);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:t.source,...t.description===void 0?{}:{description:t.description}}))}else if(e.kind===`file`&&this.cwd!==void 0&&this.cwd!==``){let n=await Cs.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(MD);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=lf(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}}currentTrigger(){return cf(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=uD(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,n)}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return dD(t,this.mobilePromptEnterMedia,sD())?(this.send(this.canSteer||this.isCompacting?`followUp`:void 0),!0):te(e)||f(e)}handleEditorTab(e){if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):l.run?.(e)??!1}pick(e){let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,a=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:a,insert:`${e.insertText}${n}`},selection:i.cursor(r),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending||this.sendDisabled)return;let t=this.draft.trim(),n=this.attachments;if(t===``&&n.length===0)return;let r=this.canSteer||this.isCompacting?e:void 0,i=n.length>0?this.currentAttachments():void 0,a=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=AD(this.machineId,this.sessionId);e!==void 0&&id(e);let t=e===void 0?void 0:this.activeAttachmentScope();t!==void 0&&t.clear(),this.attachmentScope=void 0,this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=a_}};B([x({type:Boolean})],q.prototype,`disabled`,void 0),B([x({type:Boolean})],q.prototype,`sendDisabled`,void 0),B([x()],q.prototype,`sessionId`,void 0),B([x()],q.prototype,`cwd`,void 0),B([x()],q.prototype,`machineId`,void 0),B([x()],q.prototype,`projectId`,void 0),B([x()],q.prototype,`workspaceId`,void 0),B([x({type:Boolean})],q.prototype,`workspaceScopedFileSuggestions`,void 0),B([x({type:Boolean})],q.prototype,`canSteer`,void 0),B([x({type:Boolean})],q.prototype,`isCompacting`,void 0),B([x({type:Boolean})],q.prototype,`canStop`,void 0),B([x({attribute:!1})],q.prototype,`status`,void 0),B([x({type:Boolean})],q.prototype,`sending`,void 0),B([x({attribute:!1})],q.prototype,`onSend`,void 0),B([x({attribute:!1})],q.prototype,`onStop`,void 0),B([x({attribute:!1})],q.prototype,`onSelectModel`,void 0),B([x({attribute:!1})],q.prototype,`onSelectThinking`,void 0),B([x({attribute:!1})],q.prototype,`onCompact`,void 0),B([x({type:Boolean})],q.prototype,`showSessionConfiguration`,void 0),B([x({attribute:!1})],q.prototype,`sessionConfiguration`,void 0),B([x({attribute:!1})],q.prototype,`modelPolicyStatus`,void 0),B([x({attribute:!1})],q.prototype,`modelTierCatalog`,void 0),B([x({attribute:!1})],q.prototype,`onSelectPolicyMode`,void 0),B([x({attribute:!1})],q.prototype,`onSelectPolicyTier`,void 0),B([x({attribute:!1})],q.prototype,`onSelectPolicyThinking`,void 0),B([x({attribute:!1})],q.prototype,`policyThinkingOptions`,void 0),B([x({type:Boolean})],q.prototype,`modelPolicyLoading`,void 0),B([x({type:Boolean})],q.prototype,`modelPolicySaving`,void 0),B([x()],q.prototype,`modelPolicyError`,void 0),B([x({attribute:!1})],q.prototype,`availableThinkingLevels`,void 0),B([x({attribute:!1})],q.prototype,`attachmentDrafts`,void 0),B([C(`.markdown-editor`)],q.prototype,`editorHost`,void 0),B([C(`.attachment-input`)],q.prototype,`attachmentInput`,void 0),B([S()],q.prototype,`currentInputMode`,void 0),B([S()],q.prototype,`completions`,void 0),B([S()],q.prototype,`selectedIndex`,void 0),B([S()],q.prototype,`attachments`,void 0),B([S()],q.prototype,`attachmentDelivery`,void 0),B([S()],q.prototype,`attachmentError`,void 0),q=B([b(`prompt-editor`)],q);function DD(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel&&OD(e.modelPolicy,t.modelPolicy)&&kD(e)===kD(t)}function OD(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.mode===t.mode&&e.tier===t.tier&&e.resolved.model.provider===t.resolved.model.provider&&e.resolved.model.id===t.resolved.model.id&&e.resolved.thinkingLevel===t.resolved.thinkingLevel&&e.ladderValid===t.ladderValid&&e.blockedReason===t.blockedReason}function kD(e){return e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function AD(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return qc(e,t)}function jD(){return[]}function MD(){return[]}function ND(e){return e===null?[]:Array.from(e.files)}function PD(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function FD(e){return e.kind===`image`?{kind:`image`,mimeType:e.mimeType,data:e.data,name:e.name}:{kind:`file`,mimeType:e.mimeType,data:e.data,name:e.name}}function ID(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function LD(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(`Failed to read file`))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(`Unexpected file reader result`));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var RD={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},zD={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function BD(e){return mf(e).kind===`normal`?RD:zD}var VD=class extends y{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
|
|
3560
3562
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
3561
3563
|
<section
|
|
3562
3564
|
role="dialog"
|
|
@@ -3579,12 +3581,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3579
3581
|
`}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?`input`:`.options`)?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){let e=this.query.trim().toLowerCase();return e===``?this.options:this.options.filter(t=>`${t.label} ${t.description??``} ${t.value}`.toLowerCase().includes(e))}renderGroupedOptions(e){let t=[];for(let[n,r]of e.entries()){let e=t[t.length-1];e!==void 0&&e.group===r.group?e.items.push({option:r,index:n}):t.push({group:r.group,items:[{option:r,index:n}]})}return t.map(e=>{let t=e.group!==void 0&&e.group!==``;return g`
|
|
3580
3582
|
${t?g`<div class="group-header">${e.group}</div>`:null}
|
|
3581
3583
|
${e.items.map(({option:e,index:n})=>g`
|
|
3582
|
-
<button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${
|
|
3584
|
+
<button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${bD(n===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
|
|
3583
3585
|
<span>${e.label}</span>
|
|
3584
3586
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
3585
3587
|
</button>
|
|
3586
3588
|
`)}
|
|
3587
|
-
`})}handleDialogKeyDown(e){if(e.key===`Tab`){e.stopPropagation(),this.trapTabFocus(e);return}if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.onCancel?.();return}let t=e.target;!(t instanceof HTMLInputElement)&&!(t instanceof Element&&t.closest(`.options`)!==null)||this.handleOptionKeyDown(e)}trapTabFocus(e){let t=[...this.renderRoot.querySelectorAll(`button:not(:disabled), input:not(:disabled), [tabindex='0']`)];if(t.length===0){e.preventDefault(),this.renderRoot.querySelector(`section[role='dialog']`)?.focus();return}let n=t.findIndex(e=>e===this.shadowRoot?.activeElement),r=!e.shiftKey&&n===t.length-1,i=e.shiftKey&&n<=0;!r&&!i&&!(n<0)||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}handleOptionKeyDown(e){let t=this.filteredOptions();if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=r_}};B([x()],
|
|
3589
|
+
`})}handleDialogKeyDown(e){if(e.key===`Tab`){e.stopPropagation(),this.trapTabFocus(e);return}if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.onCancel?.();return}let t=e.target;!(t instanceof HTMLInputElement)&&!(t instanceof Element&&t.closest(`.options`)!==null)||this.handleOptionKeyDown(e)}trapTabFocus(e){let t=[...this.renderRoot.querySelectorAll(`button:not(:disabled), input:not(:disabled), [tabindex='0']`)];if(t.length===0){e.preventDefault(),this.renderRoot.querySelector(`section[role='dialog']`)?.focus();return}let n=t.findIndex(e=>e===this.shadowRoot?.activeElement),r=!e.shiftKey&&n===t.length-1,i=e.shiftKey&&n<=0;!r&&!i&&!(n<0)||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}handleOptionKeyDown(e){let t=this.filteredOptions();if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=r_}};B([x()],VD.prototype,`title`,void 0),B([x({type:Boolean})],VD.prototype,`searchable`,void 0),B([x({attribute:!1})],VD.prototype,`options`,void 0),B([x({attribute:!1})],VD.prototype,`selectedValue`,void 0),B([x({attribute:!1})],VD.prototype,`onPick`,void 0),B([x({attribute:!1})],VD.prototype,`onCancel`,void 0),B([S()],VD.prototype,`selectedIndex`,void 0),B([S()],VD.prototype,`query`,void 0),VD=B([b(`command-picker`)],VD);var HD=class extends y{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
|
|
3588
3590
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
3589
3591
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3590
3592
|
<header>
|
|
@@ -3597,7 +3599,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3597
3599
|
</header>
|
|
3598
3600
|
<div class="options">
|
|
3599
3601
|
${e.length===0?g`<div class="empty">No actions found.</div>`:e.map((e,t)=>g`
|
|
3600
|
-
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${
|
|
3602
|
+
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${bD(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
|
|
3601
3603
|
<span class="main">
|
|
3602
3604
|
<strong>${e.title}</strong>
|
|
3603
3605
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -3610,7 +3612,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3610
3612
|
</div>
|
|
3611
3613
|
</section>
|
|
3612
3614
|
</div>
|
|
3613
|
-
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return
|
|
3615
|
+
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return UD(this.actions,this.queryText)}handleKeyDown(e){let t=this.filteredActions();if(e.key===`Escape`)e.preventDefault(),this.onCancel?.();else if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n!==void 0&&this.run(n)}}run(e){e.enabled!==!1&&this.onRun?.(e)}static{this.styles=i_}};B([x({attribute:!1})],HD.prototype,`actions`,void 0),B([x({attribute:!1})],HD.prototype,`onRun`,void 0),B([x({attribute:!1})],HD.prototype,`onCancel`,void 0),B([C(`input`)],HD.prototype,`input`,void 0),B([S()],HD.prototype,`queryText`,void 0),B([S()],HD.prototype,`selectedIndex`,void 0),HD=B([b(`action-palette`)],HD);function UD(e,t){let n=t.trim().toLowerCase();return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||[e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `).toLowerCase().includes(n))}var WD=class extends y{render(){let e=this.state;return e===void 0?null:g`
|
|
3614
3616
|
<div class="backdrop" @mousedown=${()=>{this.cancel()}}>
|
|
3615
3617
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3616
3618
|
<header>
|
|
@@ -3633,13 +3635,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3633
3635
|
<div class="actions"><button @click=${()=>{this.cancel()}}>Cancel</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?`Saving…`:`Save API key`}</button></div>
|
|
3634
3636
|
</div>
|
|
3635
3637
|
`;case`oauth`:return this.renderOAuth(e);case`logout`:return g`<div class="options">${e.providers.length===0?g`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(e=>g`
|
|
3636
|
-
<button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${
|
|
3638
|
+
<button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${KD(e.authType)}</small></button>
|
|
3637
3639
|
`)}</div>`}}renderProviderButton(e){return g`
|
|
3638
3640
|
<button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
|
|
3639
|
-
<span>${e.name}${e.status.source===void 0?null:g` <em>${
|
|
3640
|
-
<small>${e.id} · ${
|
|
3641
|
+
<span>${e.name}${e.status.source===void 0?null:g` <em>${JD(e)}</em>`}</span>
|
|
3642
|
+
<small>${e.id} · ${KD(e.authType)}</small>
|
|
3641
3643
|
</button>
|
|
3642
|
-
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=
|
|
3644
|
+
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=GD(n?.promptType);return g`
|
|
3643
3645
|
<div class="form">
|
|
3644
3646
|
${t.auth===void 0?g`<p>Starting login flow…</p>`:g`
|
|
3645
3647
|
<p>Open this authorization link:</p>
|
|
@@ -3672,7 +3674,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3672
3674
|
${t.status===`error`||t.status===`cancelled`?g`<div class="error-text">${t.error??t.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
|
|
3673
3675
|
${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
|
|
3674
3676
|
</div>
|
|
3675
|
-
`}focusInputIfNeeded(){let e=
|
|
3677
|
+
`}focusInputIfNeeded(){let e=qD(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key===`Escape`){e.preventDefault(),this.cancel();return}if(e.key!==`Enter`)return;let t=this.state;t?.step===`apiKey`?(e.preventDefault(),this.onSaveApiKey?.()):t?.step===`oauth`&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step===`oauth`?this.onOAuthCancel?.():this.onCancel?.()}static{this.styles=[r_,h`
|
|
3676
3678
|
.form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
|
|
3677
3679
|
.form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
|
|
3678
3680
|
.form a { color: var(--pi-accent); overflow-wrap: anywhere; }
|
|
@@ -3690,7 +3692,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3690
3692
|
.inline-options button { display: grid; gap: 2px; text-align: left; }
|
|
3691
3693
|
.inline-options small { color: var(--pi-muted); }
|
|
3692
3694
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
3693
|
-
`]}};B([x({attribute:!1})],
|
|
3695
|
+
`]}};B([x({attribute:!1})],WD.prototype,`state`,void 0),B([x({attribute:!1})],WD.prototype,`onChooseMethod`,void 0),B([x({attribute:!1})],WD.prototype,`onSelectProvider`,void 0),B([x({attribute:!1})],WD.prototype,`onApiKeyInput`,void 0),B([x({attribute:!1})],WD.prototype,`onSaveApiKey`,void 0),B([x({attribute:!1})],WD.prototype,`onLogoutProvider`,void 0),B([x({attribute:!1})],WD.prototype,`onOAuthInput`,void 0),B([x({attribute:!1})],WD.prototype,`onOAuthRespond`,void 0),B([x({attribute:!1})],WD.prototype,`onOAuthCancel`,void 0),B([x({attribute:!1})],WD.prototype,`onCancel`,void 0),B([C(`input`)],WD.prototype,`input`,void 0),WD=B([b(`auth-dialog`)],WD);function GD(e){return e===`secret`?`password`:`text`}function KD(e){return e===`oauth`?`subscription`:`credentials`}function qD(e){if(e?.step===`apiKey`)return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step===`oauth`&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function JD(e){if(e.status.source===void 0)return``;switch(e.status.source){case`stored`:return`✓ configured`;case`environment`:return`✓ env${e.status.label===void 0?``:`: ${e.status.label}`}`;case`runtime`:return`✓ runtime`;case`fallback`:return`✓ custom key`;case`models_json_key`:return`✓ models.json key`;case`models_json_command`:return`✓ models.json command`;default:return``}}var YD=[`openai-completions`,`openai-responses`,`anthropic-messages`,`google-generative-ai`];function XD(e){return YD.map(t=>({api:t,selected:t===e}))}function ZD(e,t){return e.map(e=>({candidate:e,selected:e.id===t}))}var QD=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function $D(e){let t=e.providers??{},n=uO(t);return{config:sO(e,{...t,[n]:{api:`openai-completions`}}),providerName:n}}function eO(e,t,n){let r=n.trim(),i=e.providers??{};if(r===``)return{config:e,error:`Provider name is required.`};if(t===r)return{config:e};if(i[t]===void 0)return{config:e,error:`Provider "${t}" no longer exists.`};if(i[r]!==void 0)return{config:e,error:`A provider named "${r}" already exists.`};let a={};for(let[e,n]of Object.entries(i))a[e===t?r:e]=n;return{config:sO(e,a)}}function tO(e,t,n){let r=e.providers??{};return r[t]===void 0?e:sO(e,{...r,[t]:n})}function nO(e,t){let n=e.providers??{};return n[t]===void 0?e:sO(e,cO(n,t))}function rO(e,t){let n=e.providers?.[t];if(n===void 0)return e;let r=[...n.models??[],{id:``}];return tO(e,t,{...n,models:r})}function iO(e,t,n,r){let i=e.providers?.[t],a=i?.models;if(i===void 0||a===void 0||n<0||n>=a.length)return e;let o=[...a];return o[n]=r,tO(e,t,{...i,models:o})}function aO(e,t,n){let r=e.providers?.[t],i=r?.models;if(r===void 0||i===void 0||n<0||n>=i.length)return e;let a=i.filter((e,t)=>t!==n);if(a.length===0){let n={...r};return delete n.models,tO(e,t,n)}return tO(e,t,{...r,models:a})}function oO(e,t,n,r){let i=n==="default"?lO(e??{},t):{...e??{}};if(n===`disabled`&&(i[t]=null),n===`custom`){let e=r?.trim();i[t]=e===void 0||e===``?t:e}return Object.keys(i).length===0?void 0:i}function sO(e,t){return{...e,providers:t}}function cO(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function lO(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function uO(e){let t=`new-provider`,n=1;for(;e[t]!==void 0;)t=`new-provider-${String(n++)}`;return t}var dO={thinkingFormat:`deepseek`,requiresReasoningContentOnAssistantMessages:!0},fO=class extends y{constructor(...e){super(...e),this.modelsApi=Qo,this.config={providers:{}},this.loading=!0,this.saving=!1,this.error=``,this.savedMessage=``,this.providerNameDraft=``,this.renameError=``,this.advancedErrors={},this.modelTests={},this.discoveredModels={},this.loadRequestSequence=0,this.modelDiscoverySequence=0,this.modelDiscoveryRequestSequences=new Map}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){e.has(`machine`)&&hO(e.get(`machine`))!==this.machineId()&&(this.resetForMachineChange(),this.isConnected&&this.loadConfig())}render(){return g`
|
|
3694
3696
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
3695
3697
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="models-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3696
3698
|
<header>
|
|
@@ -3701,10 +3703,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3701
3703
|
</div>
|
|
3702
3704
|
<div class="header-actions">
|
|
3703
3705
|
<button class="icon-button" type="button" title="Reload models configuration" aria-label="Reload models configuration" ?disabled=${this.loading} @click=${()=>{this.loadConfig()}}>
|
|
3704
|
-
${
|
|
3706
|
+
${UO()}
|
|
3705
3707
|
</button>
|
|
3706
3708
|
<button class="icon-button" type="button" title="Close models configuration" aria-label="Close models configuration" @click=${()=>{this.close()}}>
|
|
3707
|
-
${
|
|
3709
|
+
${WO()}
|
|
3708
3710
|
</button>
|
|
3709
3711
|
</div>
|
|
3710
3712
|
</header>
|
|
@@ -3722,7 +3724,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3722
3724
|
${this.savedMessage===``?null:g`<span class="saved-message">${this.savedMessage}</span>`}
|
|
3723
3725
|
</div>
|
|
3724
3726
|
<button type="button" class="secondary" @click=${()=>{this.configureAuth()}}>
|
|
3725
|
-
${
|
|
3727
|
+
${GO()} Authentication
|
|
3726
3728
|
</button>
|
|
3727
3729
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
3728
3730
|
<button type="button" class="primary" ?disabled=${this.saving||this.loading} @click=${()=>{this.saveConfig()}}>
|
|
@@ -3743,28 +3745,28 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3743
3745
|
</div>
|
|
3744
3746
|
<div class="tree-actions">
|
|
3745
3747
|
<button type="button" class="add-provider" @click=${()=>{this.addCustomProvider()}}>
|
|
3746
|
-
${
|
|
3748
|
+
${VO()} Add provider
|
|
3747
3749
|
</button>
|
|
3748
3750
|
<button type="button" class="auth-link" @click=${()=>{this.configureAuth()}}>
|
|
3749
|
-
${
|
|
3751
|
+
${GO()} Configure authentication
|
|
3750
3752
|
</button>
|
|
3751
3753
|
</div>
|
|
3752
3754
|
</aside>
|
|
3753
3755
|
`}renderProviderTreeNode(e,t){let n=this.selection?.type===`provider`&&this.selection.providerName===e,r=t.models??[];return g`
|
|
3754
3756
|
<div class="provider-node">
|
|
3755
3757
|
<button class="tree-row provider-row ${n?`selected`:``}" type="button" @click=${()=>{this.selectProvider(e)}}>
|
|
3756
|
-
${
|
|
3758
|
+
${zO()}
|
|
3757
3759
|
<span class="tree-label">${e}</span>
|
|
3758
3760
|
</button>
|
|
3759
3761
|
${r.map((t,n)=>g`
|
|
3760
3762
|
<button class="tree-row model-row ${this.selection?.type===`model`&&this.selection.providerName===e&&this.selection.index===n?`selected`:``}" type="button" @click=${()=>{this.selectModel(e,n)}}>
|
|
3761
|
-
${
|
|
3763
|
+
${BO()}
|
|
3762
3764
|
<span class="tree-label">${t.id.trim()===``?`new model`:t.id}</span>
|
|
3763
3765
|
${t.reasoning===!0?g`<span class="thinking-mark" title="Reasoning enabled">T</span>`:null}
|
|
3764
3766
|
</button>
|
|
3765
3767
|
`)}
|
|
3766
3768
|
<button class="tree-row add-model" type="button" @click=${()=>{this.addModel(e)}}>
|
|
3767
|
-
${
|
|
3769
|
+
${VO()} <span>Add model</span>
|
|
3768
3770
|
</button>
|
|
3769
3771
|
</div>
|
|
3770
3772
|
`}renderDetail(){let e=this.selection;if(e===void 0)return g`
|
|
@@ -3781,16 +3783,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3781
3783
|
</div>
|
|
3782
3784
|
<div class="provider-actions">
|
|
3783
3785
|
<button type="button" class="secondary" ?disabled=${!r||n?.phase===`discovering`} @click=${()=>{this.discoverModels(e)}}>
|
|
3784
|
-
${n?.phase===`discovering`?
|
|
3786
|
+
${n?.phase===`discovering`?qO():UO()} ${n===void 0?`Fetch models`:n.phase===`discovering`?`Fetching models...`:`Refresh models`}
|
|
3785
3787
|
</button>
|
|
3786
|
-
<button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${
|
|
3788
|
+
<button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${HO()} Delete provider</button>
|
|
3787
3789
|
</div>
|
|
3788
3790
|
</div>
|
|
3789
3791
|
|
|
3790
3792
|
<div class="field-stack provider-name-field">
|
|
3791
3793
|
<label for="provider-name">Provider name</label>
|
|
3792
3794
|
<div class="inline-field">
|
|
3793
|
-
<input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=
|
|
3795
|
+
<input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=_O(e),this.renameError=``}}>
|
|
3794
3796
|
<button type="button" class="secondary" ?disabled=${this.providerNameDraft.trim()===``||this.providerNameDraft===e} @click=${()=>{this.renameSelectedProvider(e)}}>Rename</button>
|
|
3795
3797
|
</div>
|
|
3796
3798
|
${this.renameError===``?null:g`<span class="field-error">${this.renameError}</span>`}
|
|
@@ -3798,19 +3800,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3798
3800
|
|
|
3799
3801
|
<div class="field-stack">
|
|
3800
3802
|
<label for="provider-base-url">Base URL</label>
|
|
3801
|
-
<input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:
|
|
3803
|
+
<input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:gO(_O(n))})}}>
|
|
3802
3804
|
</div>
|
|
3803
3805
|
|
|
3804
3806
|
<div class="field-stack">
|
|
3805
3807
|
<label for="provider-api-key">API key source</label>
|
|
3806
|
-
<input id="provider-api-key" class="mono" type="password" autocomplete="off" .value=${t.apiKey??``} placeholder="ENV_VAR_NAME, !command, or literal key" @input=${n=>{this.replaceProvider(e,{...t,apiKey:
|
|
3808
|
+
<input id="provider-api-key" class="mono" type="password" autocomplete="off" .value=${t.apiKey??``} placeholder="ENV_VAR_NAME, !command, or literal key" @input=${n=>{this.replaceProvider(e,{...t,apiKey:gO(_O(n))})}}>
|
|
3807
3809
|
<span class="help-text">Use an environment variable name, prefix a command with <code>!</code>, or configure built-in provider credentials through Authentication.</span>
|
|
3808
3810
|
</div>
|
|
3809
3811
|
|
|
3810
3812
|
<div class="field-stack">
|
|
3811
3813
|
<label for="provider-api">API format</label>
|
|
3812
|
-
<select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:
|
|
3813
|
-
${
|
|
3814
|
+
<select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:_O(n)})}}>
|
|
3815
|
+
${XD(i).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
|
|
3814
3816
|
</select>
|
|
3815
3817
|
</div>
|
|
3816
3818
|
|
|
@@ -3825,7 +3827,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3825
3827
|
</div>
|
|
3826
3828
|
</details>
|
|
3827
3829
|
</div>
|
|
3828
|
-
`}renderModelDetail(e,t,n,r){let i=this.modelTests[
|
|
3830
|
+
`}renderModelDetail(e,t,n,r){let i=this.modelTests[AO(e,r)];return g`
|
|
3829
3831
|
<div class="detail-content">
|
|
3830
3832
|
<div class="detail-heading">
|
|
3831
3833
|
<div>
|
|
@@ -3833,35 +3835,35 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3833
3835
|
<h2>${n.id.trim()===``?`New model`:n.id}</h2>
|
|
3834
3836
|
</div>
|
|
3835
3837
|
<div class="model-actions">
|
|
3836
|
-
${i===void 0?null:g`<span class="connection-state ${i.phase}">${
|
|
3838
|
+
${i===void 0?null:g`<span class="connection-state ${i.phase}">${FO(i)}</span>`}
|
|
3837
3839
|
<button type="button" class="secondary" ?disabled=${n.id.trim()===``||i?.phase===`testing`} @click=${()=>{this.testModel(e,r)}}>
|
|
3838
|
-
${i?.phase===`testing`?
|
|
3840
|
+
${i?.phase===`testing`?qO():KO()} ${i?.phase===`testing`?`Testing...`:`Test`}
|
|
3839
3841
|
</button>
|
|
3840
|
-
<button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${
|
|
3842
|
+
<button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${HO()} Remove</button>
|
|
3841
3843
|
</div>
|
|
3842
3844
|
</div>
|
|
3843
3845
|
|
|
3844
|
-
${i===void 0?null:g`<div class="connection-detail ${i.phase}">${
|
|
3846
|
+
${i===void 0?null:g`<div class="connection-detail ${i.phase}">${IO(i)}</div>`}
|
|
3845
3847
|
|
|
3846
3848
|
<div class="field-grid two-columns">
|
|
3847
3849
|
${this.renderModelIdField(e,n,r)}
|
|
3848
3850
|
<div class="field-stack">
|
|
3849
3851
|
<label for="model-name">Display name</label>
|
|
3850
|
-
<input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:
|
|
3852
|
+
<input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:gO(_O(t))})}}>
|
|
3851
3853
|
</div>
|
|
3852
3854
|
</div>
|
|
3853
3855
|
|
|
3854
3856
|
<div class="field-stack">
|
|
3855
3857
|
<label for="model-api">API override</label>
|
|
3856
|
-
<select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:
|
|
3858
|
+
<select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:gO(_O(t))})}}>
|
|
3857
3859
|
<option value="">Inherit provider API</option>
|
|
3858
|
-
${
|
|
3860
|
+
${XD(n.api).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
|
|
3859
3861
|
</select>
|
|
3860
3862
|
</div>
|
|
3861
3863
|
|
|
3862
3864
|
<div class="switch-row">
|
|
3863
3865
|
${this.renderCheck(`Reasoning / thinking`,n.reasoning===!0,t=>{this.replaceModel(e,r,{...n,reasoning:t||void 0})})}
|
|
3864
|
-
${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?
|
|
3866
|
+
${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?SO(n.input):CO(n.input)})})}
|
|
3865
3867
|
</div>
|
|
3866
3868
|
|
|
3867
3869
|
${n.reasoning===!0?g`
|
|
@@ -3871,10 +3873,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3871
3873
|
<span class="section-label">Thinking configuration</span>
|
|
3872
3874
|
<p>Map Pi thinking levels to values accepted by this model, or disable a level.</p>
|
|
3873
3875
|
</div>
|
|
3874
|
-
${this.renderCheck(`DeepSeek thinking compatibility`,
|
|
3876
|
+
${this.renderCheck(`DeepSeek thinking compatibility`,wO(n),t=>{this.replaceModel(e,r,TO(n,t))})}
|
|
3875
3877
|
</div>
|
|
3876
3878
|
<div class="thinking-map">
|
|
3877
|
-
${
|
|
3879
|
+
${QD.map(t=>this.renderThinkingLevel(e,r,n,t))}
|
|
3878
3880
|
</div>
|
|
3879
3881
|
</section>
|
|
3880
3882
|
`:null}
|
|
@@ -3882,11 +3884,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3882
3884
|
<div class="field-grid two-columns">
|
|
3883
3885
|
<div class="field-stack">
|
|
3884
3886
|
<label for="context-window">Context window (tokens)</label>
|
|
3885
|
-
<input id="context-window" type="number" min="0" inputmode="numeric" .value=${
|
|
3887
|
+
<input id="context-window" type="number" min="0" inputmode="numeric" .value=${yO(n.contextWindow)} placeholder="128000" @input=${t=>{this.replaceModel(e,r,{...n,contextWindow:bO(_O(t))})}}>
|
|
3886
3888
|
</div>
|
|
3887
3889
|
<div class="field-stack">
|
|
3888
3890
|
<label for="max-tokens">Max output tokens</label>
|
|
3889
|
-
<input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${
|
|
3891
|
+
<input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${yO(n.maxTokens)} placeholder="16384" @input=${t=>{this.replaceModel(e,r,{...n,maxTokens:bO(_O(t))})}}>
|
|
3890
3892
|
</div>
|
|
3891
3893
|
</div>
|
|
3892
3894
|
|
|
@@ -3913,14 +3915,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3913
3915
|
`}renderModelIdField(e,t,n){let r=this.discoveredModels[e]?.models;if(r===void 0)return g`
|
|
3914
3916
|
<div class="field-stack">
|
|
3915
3917
|
<label for="model-id">Model ID <span aria-hidden="true">*</span></label>
|
|
3916
|
-
<input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:
|
|
3918
|
+
<input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:_O(r)})}}>
|
|
3917
3919
|
</div>
|
|
3918
3920
|
`;let i=t.id.trim()===``||r.some(e=>e.id===t.id)?r:[{id:t.id,...t.name===void 0?{}:{name:t.name}},...r];return g`
|
|
3919
3921
|
<div class="field-stack">
|
|
3920
3922
|
<label for="model-id">Model ID <span aria-hidden="true">*</span></label>
|
|
3921
|
-
<select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,
|
|
3923
|
+
<select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,_O(t))}}>
|
|
3922
3924
|
${t.id.trim()===``?g`<option value="" disabled>Select a model</option>`:null}
|
|
3923
|
-
${
|
|
3925
|
+
${ZD(i,t.id).map(({candidate:e,selected:t})=>g`<option value=${e.id} .selected=${t}>${e.name===void 0?e.id:`${e.name} (${e.id})`}</option>`)}
|
|
3924
3926
|
</select>
|
|
3925
3927
|
</div>
|
|
3926
3928
|
`}renderThinkingLevel(e,t,n,r){let i=n.thinkingLevelMap?.[r],a=i===void 0?`default`:i===null?`disabled`:`custom`,o=typeof i==`string`?i:``;return g`
|
|
@@ -3932,26 +3934,26 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3932
3934
|
</div>
|
|
3933
3935
|
<label class="custom-thinking">
|
|
3934
3936
|
<span>Custom</span>
|
|
3935
|
-
<input class="mono" .value=${o} placeholder=${r} @focus=${()=>{this.setThinkingLevel(e,t,n,r,`custom`,o||r)}} @input=${i=>{this.setThinkingLevel(e,t,n,r,`custom`,
|
|
3937
|
+
<input class="mono" .value=${o} placeholder=${r} @focus=${()=>{this.setThinkingLevel(e,t,n,r,`custom`,o||r)}} @input=${i=>{this.setThinkingLevel(e,t,n,r,`custom`,_O(i))}}>
|
|
3936
3938
|
</label>
|
|
3937
3939
|
</div>
|
|
3938
3940
|
`}renderCostField(e,t,n,r,i){let a=`cost-${t}`;return g`
|
|
3939
3941
|
<div class="field-stack">
|
|
3940
3942
|
<label for=${a}>${e}</label>
|
|
3941
|
-
<input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${
|
|
3943
|
+
<input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${yO(i.cost?.[t])} placeholder="0" @input=${e=>{this.setCost(n,r,i,t,xO(_O(e)))}}>
|
|
3942
3944
|
</div>
|
|
3943
3945
|
`}renderCheck(e,t,n){return g`
|
|
3944
3946
|
<label class="check-row">
|
|
3945
|
-
<input type="checkbox" .checked=${t} @change=${e=>{n(
|
|
3947
|
+
<input type="checkbox" .checked=${t} @change=${e=>{n(vO(e))}}>
|
|
3946
3948
|
<span>${e}</span>
|
|
3947
3949
|
</label>
|
|
3948
3950
|
`}renderJsonField(e,t,n,r){let i=`advanced-${t}`,a=this.advancedErrors[t];return g`
|
|
3949
3951
|
<div class="field-stack">
|
|
3950
3952
|
<label for=${i}>${e} (JSON object)</label>
|
|
3951
|
-
<textarea id=${i} class="mono" rows="4" .value=${
|
|
3953
|
+
<textarea id=${i} class="mono" rows="4" .value=${DO(n)} @change=${e=>{r(_O(e))}}></textarea>
|
|
3952
3954
|
${a===void 0?null:g`<span class="field-error">${a}</span>`}
|
|
3953
3955
|
</div>
|
|
3954
|
-
`}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=
|
|
3956
|
+
`}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=pO(await this.modelsApi.config(t));if(!this.isCurrentLoad(e,t))return;this.config=n,this.selection=mO(this.selection,n),this.providerNameDraft=this.selection?.type===`provider`?this.selection.providerName:``,this.renameError=``,this.advancedErrors={},this.modelTests={}}catch(n){this.isCurrentLoad(e,t)&&(this.error=`Failed to load models configuration: ${RO(n)}`)}finally{this.isCurrentLoad(e,t)&&(this.loading=!1)}}async saveConfig(){if(this.saving||this.loading)return;let e=this.machineId();this.saving=!0,this.error=``,this.savedMessage=``;try{if(await this.modelsApi.save(this.config,e),e!==this.machineId())return;this.setSavedMessage(`Saved and reloaded models for ${this.machineLabel()}.`),this.onSaved?.()}catch(t){e===this.machineId()&&(this.error=`Failed to save models configuration: ${RO(t)}`)}finally{e===this.machineId()&&(this.saving=!1)}}async testModel(e,t){let n=this.config.providers?.[e],r=n?.models?.[t];if(n===void 0||r===void 0)return;let i=AO(e,t);if(r.id.trim()===``){this.modelTests={...this.modelTests,[i]:{phase:`error`,message:`Model ID is required.`}};return}let a=this.machineId();this.modelTests={...this.modelTests,[i]:{phase:`testing`}};try{let t=await this.modelsApi.test({providerName:e,provider:n,model:r},a);if(a!==this.machineId())return;this.modelTests={...this.modelTests,[i]:t.ok?{phase:`success`,result:t}:PO(t)}}catch(e){a===this.machineId()&&(this.modelTests={...this.modelTests,[i]:{phase:`error`,message:RO(e)}})}}async discoverModels(e){let t=this.config.providers?.[e];if(t===void 0)return;let n=this.nextModelDiscoveryRequest(e),r=this.machineId(),i=this.discoveredModels[e];this.error=``,this.discoveredModels={...this.discoveredModels,[e]:i?.models===void 0?{phase:`discovering`}:{phase:`discovering`,models:i.models}};try{let i=await this.modelsApi.discover({providerName:e,provider:t},r);if(!this.isCurrentModelDiscovery(n,r,e,t))return;this.discoveredModels={...this.discoveredModels,[e]:{phase:`ready`,models:i.models}}}catch(a){if(!this.isCurrentModelDiscovery(n,r,e,t))return;this.discoveredModels=i===void 0?NO(this.discoveredModels,e):{...this.discoveredModels,[e]:i},this.error=`Failed to fetch models for ${e}: ${RO(a)}`}}selectProvider(e){this.selection={type:`provider`,providerName:e},this.providerNameDraft=e,this.renameError=``}selectModel(e,t){this.selection={type:`model`,providerName:e,index:t},this.providerNameDraft=``,this.renameError=``}addCustomProvider(){let e=$D(this.config);this.config=e.config,this.selectProvider(e.providerName)}deleteProvider(e){this.clearProviderDiscovery(e),this.config=nO(this.config,e),this.modelTests=jO(this.modelTests,e);let t=Object.keys(this.config.providers??{})[0];t===void 0?(this.selection=void 0,this.providerNameDraft=``):this.selectProvider(t)}renameSelectedProvider(e){let t=eO(this.config,e,this.providerNameDraft);if(`error`in t){this.renameError=t.error;return}let n=this.providerNameDraft.trim();this.clearProviderDiscovery(e),this.config=t.config,this.modelTests=MO(this.modelTests,e,n),this.selectProvider(n)}replaceProvider(e,t){this.invalidateProviderDiscovery(e),this.config=tO(this.config,e,t),this.modelTests=jO(this.modelTests,e)}addModel(e){let t=this.config.providers?.[e]?.models?.length??0;this.config=rO(this.config,e),this.selectModel(e,t)}deleteModel(e,t){this.config=aO(this.config,e,t),this.modelTests=jO(this.modelTests,e),this.selectProvider(e)}replaceModel(e,t,n){this.config=iO(this.config,e,t,n);let r=AO(e,t);this.modelTests[r]!==void 0&&(this.modelTests=NO(this.modelTests,r))}selectDiscoveredModel(e,t,n){let r=this.config.providers?.[e]?.models?.[t],i=this.discoveredModels[e]?.models?.find(e=>e.id===n);r===void 0||i===void 0||this.replaceModel(e,t,{...r,id:i.id,name:i.name??i.id})}invalidateProviderDiscovery(e){this.nextModelDiscoveryRequest(e);let t=this.discoveredModels[e];if(t?.phase===`discovering`){if(t.models===void 0){this.discoveredModels=NO(this.discoveredModels,e);return}this.discoveredModels={...this.discoveredModels,[e]:{phase:`ready`,models:t.models}}}}clearProviderDiscovery(e){this.nextModelDiscoveryRequest(e),this.discoveredModels[e]!==void 0&&(this.discoveredModels=NO(this.discoveredModels,e))}setThinkingLevel(e,t,n,r,i,a){this.replaceModel(e,t,{...n,thinkingLevelMap:oO(n.thinkingLevelMap,r,i,a)})}setCost(e,t,n,r,i){let a={...n.cost??{},[r]:i};if(Object.values(a).every(e=>e===void 0)){this.replaceModel(e,t,{...n,cost:void 0});return}this.replaceModel(e,t,{...n,cost:a})}updateProviderHeaders(e,t,n){let r=EO(n),i=`headers`;if(!r.ok){this.setAdvancedError(i,r.error);return}if(r.value!==void 0&&!OO(r.value)){this.setAdvancedError(i,`Headers must map string names to string values.`);return}this.clearAdvancedError(i),this.replaceProvider(e,{...t,headers:r.value===void 0?void 0:kO(r.value)})}updateProviderObject(e,t,n,r){let i=EO(r),a=n===`compat`?`compat`:`model-overrides`;if(!i.ok){this.setAdvancedError(a,i.error);return}this.clearAdvancedError(a),this.replaceProvider(e,{...t,[n]:i.value})}updateModelObject(e,t,n,r,i){let a=EO(i),o=`model-compat`;if(!a.ok){this.setAdvancedError(o,a.error);return}this.clearAdvancedError(o),this.replaceModel(e,t,{...n,[r]:a.value})}setAdvancedError(e,t){this.advancedErrors={...this.advancedErrors,[e]:t}}clearAdvancedError(e){this.advancedErrors[e]!==void 0&&(this.advancedErrors=NO(this.advancedErrors,e))}configureAuth(){this.onConfigureAuth?.()}close(){this.onClose?.()}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}resetForMachineChange(){this.loadRequestSequence+=1,this.modelDiscoveryRequestSequences.clear(),this.config={providers:{}},this.loading=!0,this.saving=!1,this.error=``,this.savedMessage=``,this.selection=void 0,this.providerNameDraft=``,this.renameError=``,this.advancedErrors={},this.modelTests={},this.discoveredModels={}}machineId(){return hO(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}isCurrentLoad(e,t){return e===this.loadRequestSequence&&t===this.machineId()}isCurrentModelDiscovery(e,t,n,r){return e===this.modelDiscoveryRequestSequences.get(n)&&t===this.machineId()&&this.config.providers?.[n]===r}nextModelDiscoveryRequest(e){let t=++this.modelDiscoverySequence;return this.modelDiscoveryRequestSequences.set(e,t),t}setSavedMessage(e){this.savedMessageTimer!==void 0&&clearTimeout(this.savedMessageTimer),this.savedMessage=e,this.savedMessageTimer=setTimeout(()=>{this.savedMessage=``,this.savedMessageTimer=void 0},3e3)}static{this.styles=h`
|
|
3955
3957
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
3956
3958
|
.backdrop { position: absolute; inset: 0; display: grid; place-items: center; box-sizing: border-box; padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); background: var(--pi-overlay); }
|
|
3957
3959
|
.dialog { width: min(920px, 100%); height: min(78dvh, 760px); max-height: 100%; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); }
|
|
@@ -4059,16 +4061,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4059
4061
|
.thinking-row { grid-template-columns: 58px minmax(0, 1fr); }
|
|
4060
4062
|
.custom-thinking { grid-column: 1 / -1; }
|
|
4061
4063
|
}
|
|
4062
|
-
`}};B([x({attribute:!1})],
|
|
4064
|
+
`}};B([x({attribute:!1})],fO.prototype,`machine`,void 0),B([x({attribute:!1})],fO.prototype,`modelsApi`,void 0),B([x({attribute:!1})],fO.prototype,`onClose`,void 0),B([x({attribute:!1})],fO.prototype,`onConfigureAuth`,void 0),B([x({attribute:!1})],fO.prototype,`onSaved`,void 0),B([S()],fO.prototype,`config`,void 0),B([S()],fO.prototype,`loading`,void 0),B([S()],fO.prototype,`saving`,void 0),B([S()],fO.prototype,`error`,void 0),B([S()],fO.prototype,`savedMessage`,void 0),B([S()],fO.prototype,`selection`,void 0),B([S()],fO.prototype,`providerNameDraft`,void 0),B([S()],fO.prototype,`renameError`,void 0),B([S()],fO.prototype,`advancedErrors`,void 0),B([S()],fO.prototype,`modelTests`,void 0),B([S()],fO.prototype,`discoveredModels`,void 0),fO=B([b(`models-config-dialog`)],fO);function pO(e){return e.providers===void 0?{...e,providers:{}}:e}function mO(e,t){if(e?.type===`provider`&&t.providers?.[e.providerName]!==void 0||e?.type===`model`&&t.providers?.[e.providerName]?.models?.[e.index]!==void 0)return e;let n=Object.keys(t.providers??{})[0];return n===void 0?void 0:{type:`provider`,providerName:n}}function hO(e){if(!LO(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function gO(e){return e.trim()===``?void 0:e}function _O(e){let t=e.target;return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.value:``}function vO(e){return e.target instanceof HTMLInputElement&&e.target.checked}function yO(e){return e===void 0?``:String(e)}function bO(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isInteger(n)&&n>=0?n:void 0}function xO(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function SO(e){let t=e??[`text`];return t.includes(`image`)?[...t]:[...t,`image`]}function CO(e){let t=(e??[]).filter(e=>e!==`image`);return t.length===0?void 0:t}function wO(e){return e.compat?.thinkingFormat===`deepseek`}function TO(e,t){if(t)return{...e,compat:{...e.compat??{},...dO}};if(e.compat===void 0)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length===0?void 0:n}}function EO(e){if(e.trim()===``)return{ok:!0,value:void 0};try{let t=JSON.parse(e);return LO(t)?{ok:!0,value:t}:{ok:!1,error:`Value must be a JSON object.`}}catch(e){return{ok:!1,error:`Invalid JSON: ${RO(e)}`}}}function DO(e){return e===void 0?``:JSON.stringify(e,null,2)}function OO(e){return Object.values(e).every(e=>typeof e==`string`)}function kO(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function AO(e,t){return`${e}\u0000${String(t)}`}function jO(e,t){let n=`${t}\u0000`,r={};for(let[t,i]of Object.entries(e))t.startsWith(n)||(r[t]=i);return r}function MO(e,t,n){let r=`${t}\u0000`,i=`${n}\u0000`,a={};for(let[t,n]of Object.entries(e)){let e=t.startsWith(r)?`${i}${t.slice(r.length)}`:t;a[e]=n}return a}function NO(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function PO(e){return{phase:`error`,message:e.error??`Model returned an error.`,...e.latencyMs===void 0?{}:{latencyMs:e.latencyMs},...e.status===void 0?{}:{status:e.status}}}function FO(e){return e.phase===`testing`?`Testing connection`:e.phase===`success`?e.result.latencyMs===void 0?`Connected`:`Connected in ${String(e.result.latencyMs)} ms`:`Connection failed`}function IO(e){if(e.phase===`testing`)return`Sending a small test request...`;if(e.phase===`success`){let t=[e.result.status===void 0?void 0:`HTTP ${String(e.result.status)}`,e.result.latencyMs===void 0?void 0:`${String(e.result.latencyMs)} ms`,e.result.responseText===void 0||e.result.responseText===``?void 0:e.result.responseText].filter(e=>e!==void 0);return t.length===0?`Connection succeeded.`:t.join(` - `)}return[e.status===void 0?void 0:`HTTP ${String(e.status)}`,e.latencyMs===void 0?void 0:`${String(e.latencyMs)} ms`,e.message].filter(e=>e!==void 0).join(` - `)}function LO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function RO(e){return e instanceof Error?e.message:String(e)}function zO(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="4" y="4" width="16" height="16" rx="2"></rect><rect x="9" y="9" width="6" height="6"></rect><path d="M9 1v3m6-3v3M9 20v3m6-3v3M20 9h3m-3 5h3M1 9h3m-3 5h3"></path></svg>`}function BO(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="7"></circle><path d="M12 8v4l3 2"></path></svg>`}function VO(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function HO(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M4 7h16M10 11v6m4-6v6M9 7l1-3h4l1 3m-9 0 1 13h10l1-13"></path></svg>`}function UO(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M20 11a8 8 0 1 0 2 5.5"></path><path d="M20 4v7h-7"></path></svg>`}function WO(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}function GO(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="8" cy="15" r="4"></circle><path d="m11 12 9-9m-3 0h3v3"></path></svg>`}function KO(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 22v-5M8 4v5m8-5v5M7 9h10v3a5 5 0 0 1-10 0V9Z"></path></svg>`}function qO(){return _`<svg class="svg-icon spin" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="8" opacity=".25"></circle><path d="M20 12a8 8 0 0 0-8-8"></path></svg>`}var J=class extends y{constructor(...e){super(...e),this.cwd=``,this.skillsApi=os,this.skills=[],this.loading=!0,this.loadError=``,this.togglingPaths=new Set,this.saveError=``,this.addMode=!1,this.searchQuery=``,this.searchResults=[],this.searching=!1,this.searchError=``,this.installError=``,this.newlyInstalledKeys=new Set,this.installScope=`global`,this.updateStatuses={},this.checkingUpdateKeys=new Set,this.checkingAll=!1,this.updateError=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSkills()}updated(e){let t=e.has(`machine`)&&JO(e.get(`machine`))!==this.machineId(),n=e.has(`cwd`)&&e.get(`cwd`)!==this.cwd;(t||n)&&(this.resetForTargetChange(),this.isConnected&&this.loadSkills())}render(){let e=this.selectedSkill();return g`
|
|
4063
4065
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
4064
4066
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="skills-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
4065
4067
|
<header>
|
|
4066
4068
|
<div class="title-block">
|
|
4067
4069
|
<h1 id="skills-dialog-title">Skills</h1>
|
|
4068
|
-
<span class="target"><code>${
|
|
4070
|
+
<span class="target"><code>${QO(this.cwd)}</code> on ${this.machineLabel()}</span>
|
|
4069
4071
|
</div>
|
|
4070
4072
|
<button class="icon-button" type="button" title="Close skills configuration" aria-label="Close skills configuration" @click=${()=>{this.close()}}>
|
|
4071
|
-
${
|
|
4073
|
+
${pk()}
|
|
4072
4074
|
</button>
|
|
4073
4075
|
</header>
|
|
4074
4076
|
|
|
@@ -4094,21 +4096,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4094
4096
|
</div>
|
|
4095
4097
|
<div class="skill-list-actions">
|
|
4096
4098
|
<button class="add-skill" type="button" ?aria-pressed=${this.addMode} @click=${()=>{this.openAddMode()}}>
|
|
4097
|
-
${
|
|
4099
|
+
${fk()} Add skill
|
|
4098
4100
|
</button>
|
|
4099
4101
|
</div>
|
|
4100
4102
|
</aside>
|
|
4101
|
-
`}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=
|
|
4103
|
+
`}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=nk(e,this.updateStatuses);return g`
|
|
4102
4104
|
<button class="skill-row ${t?`selected`:``}" type="button" @click=${()=>{this.selectSkill(e)}}>
|
|
4103
4105
|
<span class="skill-indicator ${e.disableModelInvocation?`disabled`:``}" aria-hidden="true"></span>
|
|
4104
4106
|
<span class="skill-name">${e.name}</span>
|
|
4105
4107
|
${n?.state===`update-available`?g`<span class="update-available-mark" title="Update available" aria-label="Update available">↑</span>`:null}
|
|
4106
4108
|
</button>
|
|
4107
|
-
`}renderSkillDetail(e){let t=
|
|
4109
|
+
`}renderSkillDetail(e){let t=XO(e),n=tk(e),r=n===void 0?void 0:this.updateStatuses[n],i=n!==void 0&&this.checkingUpdateKeys.has(n),a=n!==void 0&&this.updatingKey===n,o=!e.disableModelInvocation;return g`
|
|
4108
4110
|
<div class="detail-content">
|
|
4109
4111
|
<div class="skill-meta-row">
|
|
4110
4112
|
<span class="scope-tag ${t}">${t}</span>
|
|
4111
|
-
<code class="skill-path" title=${e.filePath}>${
|
|
4113
|
+
<code class="skill-path" title=${e.filePath}>${ZO(e,this.cwd)}</code>
|
|
4112
4114
|
<button
|
|
4113
4115
|
class="skill-toggle ${o?`enabled`:``}"
|
|
4114
4116
|
type="button"
|
|
@@ -4126,7 +4128,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4126
4128
|
<section class="detail-section">
|
|
4127
4129
|
<h2>Source</h2>
|
|
4128
4130
|
<a class="source-link" href=${e.install.skillsShUrl} target="_blank" rel="noreferrer" title=${e.install.skillsShUrl}>
|
|
4129
|
-
<code>${
|
|
4131
|
+
<code>${$O(e.install.skillsShUrl)} ↗</code>
|
|
4130
4132
|
</a>
|
|
4131
4133
|
</section>
|
|
4132
4134
|
`}
|
|
@@ -4135,13 +4137,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4135
4137
|
<section class="detail-section">
|
|
4136
4138
|
<h2>Version</h2>
|
|
4137
4139
|
<div class="version-row">
|
|
4138
|
-
<code>${
|
|
4140
|
+
<code>${ek(r?.currentVersion??e.install.versionHash)}</code>
|
|
4139
4141
|
${e.install.canCheckForUpdates?g`
|
|
4140
4142
|
<button type="button" class="secondary compact-button" ?disabled=${i||a} @click=${()=>{this.checkForUpdates(e)}}>
|
|
4141
4143
|
${i?`Checking...`:`Check`}
|
|
4142
4144
|
</button>
|
|
4143
4145
|
`:null}
|
|
4144
|
-
${r?.state===`update-available`?g`<code class="update-version">${
|
|
4146
|
+
${r?.state===`update-available`?g`<code class="update-version">${ek(r.latestVersion)}</code>`:null}
|
|
4145
4147
|
${this.renderUpdateStatus(r,i)}
|
|
4146
4148
|
${r?.state===`update-available`?g`
|
|
4147
4149
|
<button type="button" class="primary compact-button" ?disabled=${a||i} @click=${()=>{this.updateInstalledSkill(e)}}>
|
|
@@ -4163,7 +4165,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4163
4165
|
<p>${e.description}</p>
|
|
4164
4166
|
</section>
|
|
4165
4167
|
</div>
|
|
4166
|
-
`}renderUpdateStatus(e,t){if(!t&&(e===void 0||e.state===`update-available`))return null;let n=t?`Checking...`:e?.state===`up-to-date`?`Up to date`:e?.state===`unsupported`?`Automatic checks unavailable`:e?.message??`Check failed`;return g`<span class="update-state ${t?`checking`:e?.state??`error`}">${n}</span>`}renderAddPanel(){let e=this.installScope===`global`?`~/.pi/agent/skills/`:`${
|
|
4168
|
+
`}renderUpdateStatus(e,t){if(!t&&(e===void 0||e.state===`update-available`))return null;let n=t?`Checking...`:e?.state===`up-to-date`?`Up to date`:e?.state===`unsupported`?`Automatic checks unavailable`:e?.message??`Check failed`;return g`<span class="update-state ${t?`checking`:e?.state??`error`}">${n}</span>`}renderAddPanel(){let e=this.installScope===`global`?`~/.pi/agent/skills/`:`${QO(this.cwd)}/.pi/skills/`;return g`
|
|
4167
4169
|
<div class="detail-content add-panel">
|
|
4168
4170
|
<div class="add-heading">
|
|
4169
4171
|
<h2>Add Skill</h2>
|
|
@@ -4175,7 +4177,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4175
4177
|
id="skill-search"
|
|
4176
4178
|
.value=${this.searchQuery}
|
|
4177
4179
|
placeholder="e.g. react, testing, deploy"
|
|
4178
|
-
@input=${e=>{this.searchQuery=
|
|
4180
|
+
@input=${e=>{this.searchQuery=lk(e)}}
|
|
4179
4181
|
@keydown=${e=>{e.key===`Enter`&&(e.preventDefault(),this.searchSkills())}}
|
|
4180
4182
|
>
|
|
4181
4183
|
<button type="button" class="primary" ?disabled=${this.searching||this.searchQuery.trim()===``} @click=${()=>{this.searchSkills()}}>
|
|
@@ -4197,7 +4199,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4197
4199
|
|
|
4198
4200
|
${this.searchResults.length>0?g`<div class="search-results">${this.searchResults.map(e=>this.renderSearchResult(e))}</div>`:this.searching||this.searchError!==``?null:g`<p class="search-hint">Search <a href="https://skills.sh" target="_blank" rel="noreferrer">skills.sh</a> to discover and install skills for your agent.</p>`}
|
|
4199
4201
|
</div>
|
|
4200
|
-
`}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=
|
|
4202
|
+
`}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=ik(e.package);return g`
|
|
4201
4203
|
<article class="search-result">
|
|
4202
4204
|
<div class="search-result-copy">
|
|
4203
4205
|
<strong>${r.skill??r.repository}</strong>
|
|
@@ -4226,7 +4228,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4226
4228
|
</div>
|
|
4227
4229
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
4228
4230
|
</footer>
|
|
4229
|
-
`}async loadSkills(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage skills.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.skillsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.skills=n.skills,this.selectedFilePath=
|
|
4231
|
+
`}async loadSkills(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage skills.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.skillsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.skills=n.skills,this.selectedFilePath=YO(this.selectedFilePath,n.skills)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load skills: ${uk(n)}`)}finally{this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loading=!1)}}async toggleSkill(e){let t=this.target();if(t===void 0||this.togglingPaths.has(e.filePath))return;let n=!e.disableModelInvocation;this.togglingPaths=ak(this.togglingPaths,e.filePath),this.saveError=``;try{if(await this.skillsApi.toggle({cwd:t.cwd,filePath:e.filePath,disableModelInvocation:n},t.machineId),!this.isCurrentTarget(t))return;this.skills=this.skills.map(t=>t.filePath===e.filePath?{...t,disableModelInvocation:n}:t)}catch(e){this.isCurrentTarget(t)&&(this.saveError=uk(e))}finally{this.isCurrentTarget(t)&&(this.togglingPaths=sk(this.togglingPaths,e.filePath))}}async searchSkills(){let e=this.searchQuery.trim();if(e===``||this.searching)return;let t=this.machineId();this.searching=!0,this.searchError=``,this.searchResults=[];try{let n=await this.skillsApi.search({query:e},t);if(t!==this.machineId())return;this.searchResults=n.results,n.results.length===0&&(this.searchError=`No skills found`)}catch(e){t===this.machineId()&&(this.searchError=uk(e))}finally{t===this.machineId()&&(this.searching=!1)}}async installSkill(e){let t=this.target();if(t===void 0||this.installingPackage!==void 0)return;let n=this.installScope;this.installingPackage=e,this.installError=``;try{if(await this.skillsApi.install({cwd:t.cwd,package:e,scope:n},t.machineId),!this.isCurrentTarget(t))return;this.newlyInstalledKeys=ak(this.newlyInstalledKeys,rk(n,e)),await this.loadSkills()}catch(e){this.isCurrentTarget(t)&&(this.installError=uk(e))}finally{this.isCurrentTarget(t)&&(this.installingPackage=void 0)}}async checkForUpdates(e){let t=this.target();if(t===void 0)return;let n=(e===void 0?this.skills.filter(e=>e.install!==void 0):[e]).flatMap(e=>{let t=tk(e);return t===void 0?[]:[t]});if(n.length!==0){this.updateError=``,this.checkingUpdateKeys=ok(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!0);try{let n=e?.install,r=await this.skillsApi.check(n===void 0?{cwd:t.cwd}:{cwd:t.cwd,package:n.package,scope:n.scope},t.machineId);if(!this.isCurrentTarget(t))return;let i={...this.updateStatuses};for(let e of r.updates)i[`${e.scope}\0${e.package}`]=e;this.updateStatuses=i}catch(e){this.isCurrentTarget(t)&&(this.updateError=uk(e))}finally{this.isCurrentTarget(t)&&(this.checkingUpdateKeys=ck(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!1))}}}async updateInstalledSkill(e){let t=this.target(),n=e.install,r=tk(e);if(!(t===void 0||n===void 0||r===void 0||this.updatingKey!==void 0)){this.updatingKey=r,this.updateError=``;try{let e=await this.skillsApi.update({cwd:t.cwd,package:n.package,scope:n.scope},t.machineId);if(!this.isCurrentTarget(t)||(await this.loadSkills(),!this.isCurrentTarget(t)))return;let i=e.skill?.install?.versionHash;this.updateStatuses={...this.updateStatuses,[r]:{package:n.package,scope:n.scope,state:`up-to-date`,...i===void 0?{}:{currentVersion:i,latestVersion:i}}}}catch(e){this.isCurrentTarget(t)&&(this.updateError=uk(e))}finally{this.isCurrentTarget(t)&&(this.updatingKey=void 0)}}}selectSkill(e){this.selectedFilePath=e.filePath,this.addMode=!1,this.saveError=``,this.updateError=``}openAddMode(){this.addMode=!0,this.updateComplete.then(()=>{this.searchInput?.focus()})}selectedSkill(){return this.skills.find(e=>e.filePath===this.selectedFilePath)}skillGroups(){return[{label:`project / skills.sh`,matches:e=>XO(e)===`project`&&e.install?.skillsShUrl!==void 0},{label:`project`,matches:e=>XO(e)===`project`&&e.install?.skillsShUrl===void 0},{label:`global / skills.sh`,matches:e=>XO(e)===`global`&&e.install?.skillsShUrl!==void 0},{label:`global`,matches:e=>XO(e)===`global`&&e.install?.skillsShUrl===void 0},{label:`path`,matches:e=>XO(e)===`path`}].flatMap(e=>{let t=this.skills.filter(e.matches);return t.length===0?[]:[{label:e.label,skills:t}]})}isInstalled(e,t){return this.skills.some(n=>n.install?.scope===t&&n.install.package===e)||this.newlyInstalledKeys.has(rk(t,e))}target(){return this.cwd===``?void 0:{cwd:this.cwd,machineId:this.machineId()}}isCurrentTarget(e){return e.cwd===this.cwd&&e.machineId===this.machineId()}machineId(){return JO(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}resetForTargetChange(){this.loadRequestSequence+=1,this.skills=[],this.loading=!0,this.loadError=``,this.selectedFilePath=void 0,this.togglingPaths=new Set,this.saveError=``,this.addMode=!1,this.searchQuery=``,this.searchResults=[],this.searching=!1,this.searchError=``,this.installingPackage=void 0,this.installError=``,this.newlyInstalledKeys=new Set,this.installScope=`global`,this.updateStatuses={},this.checkingUpdateKeys=new Set,this.checkingAll=!1,this.updatingKey=void 0,this.updateError=``}static{this.styles=h`
|
|
4230
4232
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
4231
4233
|
.backdrop { position: absolute; inset: 0; display: grid; place-items: center; box-sizing: border-box; padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); background: var(--pi-overlay); }
|
|
4232
4234
|
.dialog { width: min(860px, 100%); height: min(78dvh, 760px); max-height: 100%; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); }
|
|
@@ -4327,16 +4329,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4327
4329
|
.scope-row { align-items: flex-start; flex-direction: column; gap: 6px; }
|
|
4328
4330
|
.search-result { align-items: flex-start; }
|
|
4329
4331
|
}
|
|
4330
|
-
`}};B([x({attribute:!1})],J.prototype,`machine`,void 0),B([x({type:String})],J.prototype,`cwd`,void 0),B([x({attribute:!1})],J.prototype,`skillsApi`,void 0),B([x({attribute:!1})],J.prototype,`onClose`,void 0),B([S()],J.prototype,`skills`,void 0),B([S()],J.prototype,`loading`,void 0),B([S()],J.prototype,`loadError`,void 0),B([S()],J.prototype,`selectedFilePath`,void 0),B([S()],J.prototype,`togglingPaths`,void 0),B([S()],J.prototype,`saveError`,void 0),B([S()],J.prototype,`addMode`,void 0),B([S()],J.prototype,`searchQuery`,void 0),B([S()],J.prototype,`searchResults`,void 0),B([S()],J.prototype,`searching`,void 0),B([S()],J.prototype,`searchError`,void 0),B([S()],J.prototype,`installingPackage`,void 0),B([S()],J.prototype,`installError`,void 0),B([S()],J.prototype,`newlyInstalledKeys`,void 0),B([S()],J.prototype,`installScope`,void 0),B([S()],J.prototype,`updateStatuses`,void 0),B([S()],J.prototype,`checkingUpdateKeys`,void 0),B([S()],J.prototype,`checkingAll`,void 0),B([S()],J.prototype,`updatingKey`,void 0),B([S()],J.prototype,`updateError`,void 0),B([C(`#skill-search`)],J.prototype,`searchInput`,void 0),J=B([b(`skills-config-dialog`)],J);function
|
|
4332
|
+
`}};B([x({attribute:!1})],J.prototype,`machine`,void 0),B([x({type:String})],J.prototype,`cwd`,void 0),B([x({attribute:!1})],J.prototype,`skillsApi`,void 0),B([x({attribute:!1})],J.prototype,`onClose`,void 0),B([S()],J.prototype,`skills`,void 0),B([S()],J.prototype,`loading`,void 0),B([S()],J.prototype,`loadError`,void 0),B([S()],J.prototype,`selectedFilePath`,void 0),B([S()],J.prototype,`togglingPaths`,void 0),B([S()],J.prototype,`saveError`,void 0),B([S()],J.prototype,`addMode`,void 0),B([S()],J.prototype,`searchQuery`,void 0),B([S()],J.prototype,`searchResults`,void 0),B([S()],J.prototype,`searching`,void 0),B([S()],J.prototype,`searchError`,void 0),B([S()],J.prototype,`installingPackage`,void 0),B([S()],J.prototype,`installError`,void 0),B([S()],J.prototype,`newlyInstalledKeys`,void 0),B([S()],J.prototype,`installScope`,void 0),B([S()],J.prototype,`updateStatuses`,void 0),B([S()],J.prototype,`checkingUpdateKeys`,void 0),B([S()],J.prototype,`checkingAll`,void 0),B([S()],J.prototype,`updatingKey`,void 0),B([S()],J.prototype,`updateError`,void 0),B([C(`#skill-search`)],J.prototype,`searchInput`,void 0),J=B([b(`skills-config-dialog`)],J);function JO(e){if(!dk(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function YO(e,t){return e!==void 0&&t.some(t=>t.filePath===e)?e:t[0]?.filePath}function XO(e){let t=e.sourceInfo.source,n=e.sourceInfo.scope;return n===`user`||t===`user`?`global`:n===`project`||t===`project`?`project`:`path`}function ZO(e,t){return XO(e)===`project`&&e.filePath.startsWith(t)?`./${e.filePath.slice(t.length).replace(/^[/\\]/u,``)}`:QO(e.filePath)}function QO(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function $O(e){return e.replace(/^https?:\/\//u,``)}function ek(e){return e===void 0||e===``?`unknown`:e.slice(0,8)}function tk(e){return e.install===void 0?void 0:`${e.install.scope}\0${e.install.package}`}function nk(e,t){let n=tk(e);return n===void 0?void 0:t[n]}function rk(e,t){return`${e}\0${t}`}function ik(e){let t=e.lastIndexOf(`@`);return t<0?{repository:e,skill:void 0}:{repository:e.slice(0,t),skill:e.slice(t+1)}}function ak(e,t){return new Set([...e,t])}function ok(e,t){return new Set([...e,...t])}function sk(e,t){let n=new Set(e);return n.delete(t),n}function ck(e,t){let n=new Set(e);for(let e of t)n.delete(e);return n}function lk(e){let t=e.target;return t instanceof HTMLInputElement?t.value:``}function uk(e){return e instanceof Error?e.message:String(e)}function dk(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fk(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function pk(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}var mk=class extends y{constructor(...e){super(...e),this.cwd=``,this.pluginsApi=ds,this.sessionsApi=hs,this.loading=!0,this.loadError=``,this.addMode=!1,this.installSource=``,this.installScope=`global`,this.actionError=``,this.actionMessage=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadPlugins()}updated(e){let t=e.has(`machine`)&&Sk(e.get(`machine`))!==this.machineId(),n=e.has(`cwd`)&&e.get(`cwd`)!==this.cwd;!t&&!n||(this.resetForTargetChange(),this.isConnected&&this.loadPlugins())}render(){let e=this.selectedPackage();return g`
|
|
4331
4333
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
4332
4334
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="plugins-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
4333
4335
|
<header>
|
|
4334
4336
|
<div class="title-block">
|
|
4335
4337
|
<h1 id="plugins-dialog-title">Plugins</h1>
|
|
4336
|
-
<span class="target"><code>${
|
|
4338
|
+
<span class="target"><code>${Ck(this.cwd)}</code> on ${this.machineLabel()}</span>
|
|
4337
4339
|
</div>
|
|
4338
4340
|
<button class="icon-button" type="button" title="Close Plugins configuration" aria-label="Close Plugins configuration" @click=${()=>{this.close()}}>
|
|
4339
|
-
${
|
|
4341
|
+
${kk()}
|
|
4340
4342
|
</button>
|
|
4341
4343
|
</header>
|
|
4342
4344
|
|
|
@@ -4362,20 +4364,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4362
4364
|
</div>
|
|
4363
4365
|
<div class="package-list-actions">
|
|
4364
4366
|
<button class="add-plugin" type="button" aria-pressed=${String(this.addMode)} @click=${()=>{this.openAddMode()}}>
|
|
4365
|
-
${
|
|
4367
|
+
${Ok()} Add plugin
|
|
4366
4368
|
</button>
|
|
4367
4369
|
</div>
|
|
4368
4370
|
</aside>
|
|
4369
|
-
`}renderPackageListItem(e){let t=
|
|
4371
|
+
`}renderPackageListItem(e){let t=hk(e),n=!this.addMode&&t===this.selectedKey;return g`
|
|
4370
4372
|
<button class="package-row ${n?`selected`:``}" type="button" aria-pressed=${String(n)} @click=${()=>{this.selectPackage(e)}}>
|
|
4371
|
-
<span class="package-indicator" style=${`background:${
|
|
4373
|
+
<span class="package-indicator" style=${`background:${bk(e.status)}`} aria-hidden="true"></span>
|
|
4372
4374
|
<span class="package-copy">
|
|
4373
4375
|
<strong>${e.source}</strong>
|
|
4374
|
-
<small>${
|
|
4375
|
-
${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${
|
|
4376
|
+
<small>${vk(e)}</small>
|
|
4377
|
+
${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${yk(e)}</small>`}
|
|
4376
4378
|
</span>
|
|
4377
4379
|
</button>
|
|
4378
|
-
`}renderPackageDetail(e){let t=
|
|
4380
|
+
`}renderPackageDetail(e){let t=hk(e),n=this.busyKey?.endsWith(t)??!1,r=this.busyKey===`reload`,i=!e.disabled;return g`
|
|
4379
4381
|
<div class="detail-content">
|
|
4380
4382
|
<div class="detail-heading">
|
|
4381
4383
|
<div class="package-title-row">
|
|
@@ -4407,12 +4409,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4407
4409
|
</div>
|
|
4408
4410
|
|
|
4409
4411
|
<dl class="metadata-grid">
|
|
4410
|
-
<dt>Status</dt><dd style=${`color:${
|
|
4411
|
-
<dt>Version</dt><dd><code>${
|
|
4412
|
+
<dt>Status</dt><dd style=${`color:${bk(e.status)}`}>${e.status}</dd>
|
|
4413
|
+
<dt>Version</dt><dd><code>${yk(e)}</code></dd>
|
|
4412
4414
|
<dt>Package</dt><dd><code>${e.packageName??`Unknown`}</code></dd>
|
|
4413
|
-
<dt>Resources</dt><dd>${
|
|
4414
|
-
<dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:
|
|
4415
|
-
<dt>Workspace</dt><dd><code>${
|
|
4415
|
+
<dt>Resources</dt><dd>${vk(e)}</dd>
|
|
4416
|
+
<dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:Ck(e.installedPath)}</code></dd>
|
|
4417
|
+
<dt>Workspace</dt><dd><code>${Ck(this.cwd)}</code></dd>
|
|
4416
4418
|
</dl>
|
|
4417
4419
|
|
|
4418
4420
|
<section class="resource-section">
|
|
@@ -4441,7 +4443,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4441
4443
|
<div class="detail-content add-panel">
|
|
4442
4444
|
<div class="add-heading">
|
|
4443
4445
|
<h2>Add Plugin</h2>
|
|
4444
|
-
<code>${this.installScope===`project`?`${
|
|
4446
|
+
<code>${this.installScope===`project`?`${Ck(this.cwd)}/.pi/agent/{npm,git}`:`~/.pi/agent/{npm,git}`}</code>
|
|
4445
4447
|
</div>
|
|
4446
4448
|
|
|
4447
4449
|
<div class="field-stack">
|
|
@@ -4450,7 +4452,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4450
4452
|
id="plugin-source"
|
|
4451
4453
|
.value=${this.installSource}
|
|
4452
4454
|
placeholder="npm:@scope/package"
|
|
4453
|
-
@input=${e=>{this.installSource=
|
|
4455
|
+
@input=${e=>{this.installSource=Tk(e)}}
|
|
4454
4456
|
@keydown=${t=>{t.key!==`Enter`||this.installSource.trim()===``||e||(t.preventDefault(),this.installPlugin())}}
|
|
4455
4457
|
>
|
|
4456
4458
|
</div>
|
|
@@ -4477,7 +4479,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4477
4479
|
`}renderFooter(){let e=this.data,t=e?.diagnostics??[],n=this.busyKey!==void 0;return g`
|
|
4478
4480
|
<footer>
|
|
4479
4481
|
<div class="footer-summary">
|
|
4480
|
-
${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(
|
|
4482
|
+
${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(wk).join(`
|
|
4481
4483
|
`)}>
|
|
4482
4484
|
${String(t.length)} diagnostic${t.length===1?``:`s`}
|
|
4483
4485
|
</span>`:e===void 0?null:g`<span>${String(e.totals.extensions)} ext · ${String(e.totals.skills)} skills · ${String(e.totals.prompts)} prompts · ${String(e.totals.themes)} themes</span>`}
|
|
@@ -4485,7 +4487,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4485
4487
|
<button type="button" class="secondary" ?disabled=${this.loading||n} @click=${()=>{this.loadPlugins()}}>Refresh</button>
|
|
4486
4488
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
4487
4489
|
</footer>
|
|
4488
|
-
`}async loadPlugins(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage plugins.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.pluginsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.data=n,this.addMode=n.packages.length===0||this.addMode,this.selectedKey=
|
|
4490
|
+
`}async loadPlugins(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage plugins.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.pluginsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.data=n,this.addMode=n.packages.length===0||this.addMode,this.selectedKey=gk(this.selectedKey,n.packages)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load plugins: ${Ek(n)}`)}finally{this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loading=!1)}}async runAction(e,t){let n=this.target();if(n===void 0||this.busyKey!==void 0)return;let r=hk(t);this.busyKey=`${e}:${r}`,this.actionError=``,this.actionMessage=``;try{let r=await this.pluginsApi.mutate({action:e,source:t.source,scope:t.scope,cwd:n.cwd},n.machineId);if(!this.isCurrentTarget(n))return;this.data=r,e===`remove`?(this.selectedKey=gk(void 0,r.packages),r.packages.length===0&&(this.addMode=!0),this.actionMessage=`Package removed.`):this.actionMessage=xk(e)}catch(e){this.isCurrentTarget(n)&&(this.actionError=Ek(e))}finally{this.isCurrentTarget(n)&&(this.busyKey=void 0)}}async installPlugin(){let e=this.target(),t=this.installSource.trim();if(e===void 0||t===``||this.busyKey!==void 0)return;let n=this.installScope,r=`${n}\0${t}`;this.busyKey=`install:${r}`,this.actionError=``,this.actionMessage=``;try{let i=await this.pluginsApi.mutate({action:`install`,source:t,scope:n,cwd:e.cwd},e.machineId);if(!this.isCurrentTarget(e))return;this.data=i;let a=_k(i.packages,t,n);this.selectedKey=a===void 0?r:hk(a),this.addMode=!1,this.installSource=``,this.actionMessage=`Package installed.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=Ek(t))}finally{this.isCurrentTarget(e)&&(this.busyKey=void 0)}}async reloadSession(){let e=this.target(),t=this.session;if(!(e===void 0||t===void 0||this.busyKey!==void 0)){this.busyKey=`reload`,this.actionError=``,this.actionMessage=``;try{let n=await this.sessionsApi.runCommand(t,`/reload`,e.machineId);if(n.type!==`done`)throw Error(n.type===`unsupported`?n.message:`Session runtime reload did not complete.`);if(!this.isCurrentTarget(e)||(await this.onReloaded?.(),await this.loadPlugins(),!this.isCurrentTarget(e)))return;this.actionMessage=`Session reloaded.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=Ek(t))}finally{this.isCurrentTarget(e)&&(this.busyKey=void 0)}}}packageGroups(){let e=this.data?.packages??[];return[`project`,`global`].flatMap(t=>{let n=e.filter(e=>e.scope===t);return n.length===0?[]:[{scope:t,packages:n}]})}selectedPackage(){return(this.data?.packages??[]).find(e=>hk(e)===this.selectedKey)}selectPackage(e){this.selectedKey=hk(e),this.addMode=!1,this.actionError=``,this.actionMessage=``}openAddMode(){this.addMode=!0,this.actionError=``,this.actionMessage=``,this.updateComplete.then(()=>{this.pluginSourceInput?.focus()})}target(){return this.cwd===``?void 0:{cwd:this.cwd,machineId:this.machineId()}}isCurrentTarget(e){return e.cwd===this.cwd&&e.machineId===this.machineId()}machineId(){return Sk(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}resetForTargetChange(){this.loadRequestSequence+=1,this.data=void 0,this.loading=!0,this.loadError=``,this.selectedKey=void 0,this.addMode=!1,this.installSource=``,this.installScope=`global`,this.busyKey=void 0,this.actionError=``,this.actionMessage=``}static{this.styles=h`
|
|
4489
4491
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
4490
4492
|
.backdrop { position: absolute; inset: 0; display: grid; box-sizing: border-box; place-items: center; padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); background: var(--pi-overlay); }
|
|
4491
4493
|
.dialog { display: flex; width: min(860px, 100%); height: min(78dvh, 760px); max-height: 100%; flex-direction: column; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); }
|
|
@@ -4587,7 +4589,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4587
4589
|
.package-actions { width: 100%; }
|
|
4588
4590
|
.metadata-grid { grid-template-columns: 96px minmax(0, 1fr); }
|
|
4589
4591
|
}
|
|
4590
|
-
`}};B([x({attribute:!1})],
|
|
4592
|
+
`}};B([x({attribute:!1})],mk.prototype,`machine`,void 0),B([x({type:String})],mk.prototype,`cwd`,void 0),B([x({attribute:!1})],mk.prototype,`session`,void 0),B([x({attribute:!1})],mk.prototype,`pluginsApi`,void 0),B([x({attribute:!1})],mk.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],mk.prototype,`onClose`,void 0),B([x({attribute:!1})],mk.prototype,`onReloaded`,void 0),B([S()],mk.prototype,`data`,void 0),B([S()],mk.prototype,`loading`,void 0),B([S()],mk.prototype,`loadError`,void 0),B([S()],mk.prototype,`selectedKey`,void 0),B([S()],mk.prototype,`addMode`,void 0),B([S()],mk.prototype,`installSource`,void 0),B([S()],mk.prototype,`installScope`,void 0),B([S()],mk.prototype,`busyKey`,void 0),B([S()],mk.prototype,`actionError`,void 0),B([S()],mk.prototype,`actionMessage`,void 0),B([C(`#plugin-source`)],mk.prototype,`pluginSourceInput`,void 0),mk=B([b(`plugins-config-dialog`)],mk);function hk(e){return`${e.scope}\0${e.source}`}function gk(e,t){return e!==void 0&&t.some(t=>hk(t)===e)?e:t[0]===void 0?void 0:hk(t[0])}function _k(e,t,n){let r=t.trim(),i=r.startsWith(`npm:`)?r.slice(4):r;return e.find(e=>e.scope===n&&e.source===r)??e.find(e=>e.scope===n&&e.source===`npm:${i}`)??e.find(e=>e.scope===n&&e.installedPath===r)??e.find(e=>e.scope===n&&e.source.endsWith(r))}function vk(e){if(e.disabled)return`Disabled`;let t=[e.counts.extensions===0?``:`${String(e.counts.extensions)} ext`,e.counts.skills===0?``:`${String(e.counts.skills)} skills`,e.counts.prompts===0?``:`${String(e.counts.prompts)} prompts`,e.counts.themes===0?``:`${String(e.counts.themes)} themes`].filter(e=>e!==``);return t.length===0?`No resources`:t.join(` · `)}function yk(e){let t=[e.version===void 0?void 0:`installed ${e.version}`,e.configuredVersion===void 0?void 0:`configured ${e.configuredVersion}`].filter(e=>e!==void 0);return t.length===0?`Unknown`:t.join(` · `)}function bk(e){return e===`loaded`?`var(--pi-accent)`:e===`installed`?`#d97706`:e===`disabled`?`var(--pi-muted)`:`var(--pi-danger)`}function xk(e){switch(e){case`install`:return`Package installed.`;case`update`:return`Package updated.`;case`disable`:return`Package disabled.`;case`enable`:return`Package enabled.`}}function Sk(e){if(!Dk(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function Ck(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function wk(e){return`${e.type}: ${e.source===void 0?``:`${e.source}: `}${e.message}`}function Tk(e){return e.target instanceof HTMLInputElement?e.target.value:``}function Ek(e){return e instanceof Error?e.message:String(e)}function Dk(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ok(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function kk(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}var Ak=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.path=``,this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){let e=++this.requestId;this.loading=!0;try{let t=await Cs.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==``&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key===`Escape`)e.preventDefault(),this.onCancel?.();else if(e.key===`Enter`)e.preventDefault(),this.submit();else if(e.key===`ArrowDown`)e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key===`ArrowUp`)e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key===`Tab`){let t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return g`
|
|
4591
4593
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
4592
4594
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
4593
4595
|
<header>
|
|
@@ -4637,7 +4639,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4637
4639
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
4638
4640
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
4639
4641
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4640
|
-
`}};B([x({attribute:!1})],
|
|
4642
|
+
`}};B([x({attribute:!1})],Ak.prototype,`onSubmit`,void 0),B([x({attribute:!1})],Ak.prototype,`onCancel`,void 0),B([x()],Ak.prototype,`machineId`,void 0),B([S()],Ak.prototype,`path`,void 0),B([S()],Ak.prototype,`createMissing`,void 0),B([S()],Ak.prototype,`suggestions`,void 0),B([S()],Ak.prototype,`selected`,void 0),B([S()],Ak.prototype,`loading`,void 0),B([C(`input`)],Ak.prototype,`pathInput`,void 0),Ak=B([b(`project-dialog`)],Ak);var jk=class extends y{constructor(...e){super(...e),this.error=``,this.url=``,this.name=``,this.token=``,this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=``}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;let t=e.target.value,n=Mk(t);(!this.nameEdited||this.name.trim()===``||this.name===this.previousSuggestedName)&&(this.name=n),this.previousSuggestedName=n,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key===`Escape`){e.preventDefault(),this.onCancel?.();return}e.key===`Enter`&&e.target instanceof HTMLInputElement&&e.target.name===`baseUrl`&&Nk(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){let e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){let e=this.url.trim(),t=this.name.trim();if(e===``||t===``||Nk(e)!==void 0)return;let n=this.token.trim();return{name:t,baseUrl:e,...n===``?{}:{token:n}}}render(){let e=this.url.trim()!==``,t=e?Nk(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
|
|
4641
4643
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
4642
4644
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
4643
4645
|
<form @submit=${e=>{this.handleSubmit(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
@@ -4692,7 +4694,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4692
4694
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
4693
4695
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
4694
4696
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4695
|
-
`}};B([x({attribute:!1})],
|
|
4697
|
+
`}};B([x({attribute:!1})],jk.prototype,`onSubmit`,void 0),B([x({attribute:!1})],jk.prototype,`onCancel`,void 0),B([x()],jk.prototype,`error`,void 0),B([S()],jk.prototype,`url`,void 0),B([S()],jk.prototype,`name`,void 0),B([S()],jk.prototype,`token`,void 0),B([S()],jk.prototype,`submitting`,void 0),B([C(`input[name='baseUrl']`)],jk.prototype,`urlInput`,void 0),B([C(`input[name='name']`)],jk.prototype,`nameInput`,void 0),jk=B([b(`machine-dialog`)],jk);function Mk(e){let t=e.trim();if(t===``)return``;let n=Pk(t)??Pk(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):Fk(t)}function Nk(e){let t=e.trim();if(t===``)return`Remote PI WEBUI URL is required.`;let n;try{n=new URL(t)}catch{return`Enter a valid URL including http:// or https://.`}if(n.protocol!==`http:`&&n.protocol!==`https:`)return`Use an http:// or https:// URL.`;if(n.username!==``||n.password!==``)return`Do not include credentials in the machine URL.`;if(n.search!==``||n.hash!==``)return`Do not include a query string or fragment.`}function Pk(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function Fk(e){let t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,``),n=t.slice(t.lastIndexOf(`@`)+1).split(/[/?#]/u)[0]??``;return n.startsWith(`[`)&&n.includes(`]`)?n.slice(1,n.indexOf(`]`)):n.replace(/:\d+$/u,``)}var Ik={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function Lk(e){return e.tone??Ik[e.type]}var Rk=class extends y{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
|
|
4696
4698
|
<section class="panel" aria-label=${this.heading||`Settings panel`}>
|
|
4697
4699
|
<header class="section-heading">
|
|
4698
4700
|
<div class="heading-copy">
|
|
@@ -4715,7 +4717,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4715
4717
|
<div class="notice-stack" aria-label="Settings notices">
|
|
4716
4718
|
${this.notices.map(e=>this.renderNotice(e))}
|
|
4717
4719
|
</div>
|
|
4718
|
-
`}renderNotice(e){let t=
|
|
4720
|
+
`}renderNotice(e){let t=Lk(e),n=e.role??zk(t),r=e.title;return g`
|
|
4719
4721
|
<article class=${`notice ${t}`} role=${n}>
|
|
4720
4722
|
${r===void 0||r===``?v:g`<strong class="notice-title">${r}</strong>`}
|
|
4721
4723
|
<div class="notice-content">${e.content}</div>
|
|
@@ -4748,13 +4750,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4748
4750
|
.section-heading { display: grid; gap: 12px; }
|
|
4749
4751
|
.heading-actions { justify-self: start; }
|
|
4750
4752
|
}
|
|
4751
|
-
`}};B([x()],
|
|
4752
|
-
`):``}}function
|
|
4753
|
-
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function
|
|
4754
|
-
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e
|
|
4753
|
+
`}};B([x()],Rk.prototype,`heading`,void 0),B([x({attribute:!1})],Rk.prototype,`description`,void 0),B([x()],Rk.prototype,`actionLabel`,void 0),B([x()],Rk.prototype,`actionTitle`,void 0),B([x({type:Boolean})],Rk.prototype,`actionDisabled`,void 0),B([x({attribute:!1})],Rk.prototype,`notices`,void 0),B([x({attribute:!1})],Rk.prototype,`onAction`,void 0),Rk=B([b(`settings-panel-frame`)],Rk);function zk(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function Bk(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function Vk(){return{allowedPathsText:``,uploadDefaultFolder:``}}function Hk(){return{command:``,dir:``}}function Uk(e){return{host:e.host??``,port:e.port===void 0?``:String(e.port),allowedHostsMode:e.allowedHosts===!0?`all`:`list`,allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
|
|
4754
|
+
`):``}}function Wk(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
|
|
4755
|
+
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function Gk(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function Kk(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function qk(e,t){let n=Kk(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function Jk(e,t={}){let n=Xk(t),r=e.host.trim(),i=e.port.trim();if(r!==``&&(n.host=r),i!==``){let e=Number(i);if(!Number.isInteger(e)||e<1||e>65535)throw Error(`Port must be an integer from 1 to 65535.`);n.port=e}return n.allowedHosts=e.allowedHostsMode===`all`||Zk(e.allowedHostsText),n}function Yk(e){let t=Qk(e.allowedPathsText),n=$k(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function Xk(e){return{...e.shortcuts===void 0?{}:{shortcuts:e.shortcuts},...e.plugins===void 0?{}:{plugins:e.plugins},...e.pathAccess===void 0?{}:{pathAccess:e.pathAccess},...e.uploads===void 0?{}:{uploads:e.uploads},...e.maxUploadBytes===void 0?{}:{maxUploadBytes:e.maxUploadBytes},...e.spawnSessions===void 0?{}:{spawnSessions:e.spawnSessions},...e.subsessions===void 0?{}:{subsessions:e.subsessions},...e.agent===void 0?{}:{agent:e.agent}}}function Zk(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function Qk(e){let t=e.split(`
|
|
4756
|
+
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!eA(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function $k(e){let t=e.trim();if(t===``)return``;if(tA(t))throw Error(`Upload default folder must be workspace-relative.`);let n=t.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(n.length===0)return``;if(n.some(e=>e===`..`))throw Error(`Upload default folder must not contain path traversal.`);return n.join(`/`)}function eA(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function tA(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function nA(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var rA=class extends y{constructor(...e){super(...e),this.loading=!1,this.machineLoading=!1,this.saving=!1,this.error=``,this.machineError=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.gatewayDraft=Bk(),this.machineDraft=Vk(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=Uk(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=Wk(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
|
|
4755
4757
|
<settings-panel-frame
|
|
4756
4758
|
heading="General configuration"
|
|
4757
|
-
.description=${
|
|
4759
|
+
.description=${nA(this.targetLabel)}
|
|
4758
4760
|
actionLabel="Reload"
|
|
4759
4761
|
.actionDisabled=${this.loading||this.machineLoading}
|
|
4760
4762
|
.notices=${this.panelNotices()}
|
|
@@ -4783,7 +4785,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4783
4785
|
<span>Host</span>
|
|
4784
4786
|
${this.renderOverrideBadge(`host`)}
|
|
4785
4787
|
</span>
|
|
4786
|
-
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:
|
|
4788
|
+
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:oA(e)})}}>
|
|
4787
4789
|
<small>Address the web server should bind to. Leave empty to use PI WEBUI's default.</small>
|
|
4788
4790
|
</label>
|
|
4789
4791
|
|
|
@@ -4792,7 +4794,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4792
4794
|
<span>Port</span>
|
|
4793
4795
|
${this.renderOverrideBadge(`port`)}
|
|
4794
4796
|
</span>
|
|
4795
|
-
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:
|
|
4797
|
+
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:oA(e)})}}>
|
|
4796
4798
|
<small>TCP port from 1 to 65535. Leave empty to use PI WEBUI's default.</small>
|
|
4797
4799
|
</label>
|
|
4798
4800
|
|
|
@@ -4801,11 +4803,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4801
4803
|
<span>Allowed hosts</span>
|
|
4802
4804
|
${this.renderOverrideBadge(`allowedHosts`)}
|
|
4803
4805
|
</span>
|
|
4804
|
-
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:
|
|
4806
|
+
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:sA(e)===`all`?`all`:`list`})}}>
|
|
4805
4807
|
<option value="list">Only listed hosts</option>
|
|
4806
4808
|
<option value="all">Allow every host</option>
|
|
4807
4809
|
</select>
|
|
4808
|
-
<textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode===`all`} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${e=>{this.updateGatewayDraft({allowedHostsText:
|
|
4810
|
+
<textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode===`all`} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${e=>{this.updateGatewayDraft({allowedHostsText:cA(e)})}}></textarea>
|
|
4809
4811
|
<small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
|
|
4810
4812
|
</div>
|
|
4811
4813
|
|
|
@@ -4835,7 +4837,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4835
4837
|
<span class="field-heading">
|
|
4836
4838
|
<span>External filesystem roots</span>
|
|
4837
4839
|
</span>
|
|
4838
|
-
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:
|
|
4840
|
+
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:cA(e)})}}></textarea>
|
|
4839
4841
|
<small>Allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace on ${this.targetLabel}. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
|
|
4840
4842
|
</label>
|
|
4841
4843
|
|
|
@@ -4843,7 +4845,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4843
4845
|
<span class="field-heading">
|
|
4844
4846
|
<span>Default upload folder</span>
|
|
4845
4847
|
</span>
|
|
4846
|
-
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${Os} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:
|
|
4848
|
+
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${Os} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:oA(e)})}}>
|
|
4847
4849
|
<small>Workspace-relative folder for manual file uploads on ${this.targetLabel}. Leave empty to use PI WEBUI's default <code>${Os}</code>.</small>
|
|
4848
4850
|
</label>
|
|
4849
4851
|
|
|
@@ -4861,18 +4863,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4861
4863
|
<dl>
|
|
4862
4864
|
<div><dt>Host</dt><dd>${e.host??g`<span class="muted">127.0.0.1 default</span>`}</dd></div>
|
|
4863
4865
|
<div><dt>Port</dt><dd>${e.port??g`<span class="muted">8808 default</span>`}</dd></div>
|
|
4864
|
-
<div><dt>Allowed hosts</dt><dd>${
|
|
4866
|
+
<div><dt>Allowed hosts</dt><dd>${iA(e.allowedHosts)}</dd></div>
|
|
4865
4867
|
</dl>
|
|
4866
4868
|
</section>
|
|
4867
4869
|
`}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
|
|
4868
4870
|
<section class="effective-card" aria-label="Effective selected machine file access and upload summary">
|
|
4869
4871
|
<h3>Effective selected-machine settings</h3>
|
|
4870
4872
|
<dl>
|
|
4871
|
-
<div><dt>External roots</dt><dd>${
|
|
4873
|
+
<div><dt>External roots</dt><dd>${aA(e.pathAccess?.allowedPaths)}</dd></div>
|
|
4872
4874
|
<div><dt>Upload folder</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">${`.pi-webui/uploads`} default</span>`}</dd></div>
|
|
4873
4875
|
</dl>
|
|
4874
4876
|
</section>
|
|
4875
|
-
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(
|
|
4877
|
+
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(Jk(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=lA(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(Yk(this.machineDraft))}catch(e){this.machineLocalError=lA(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
|
|
4876
4878
|
:host { display: block; }
|
|
4877
4879
|
.card-heading { display: grid; gap: 6px; min-width: 0; }
|
|
4878
4880
|
h3, p { margin: 0; }
|
|
@@ -4911,10 +4913,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4911
4913
|
@media (max-width: 760px) {
|
|
4912
4914
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
4913
4915
|
}
|
|
4914
|
-
`}};B([x({attribute:!1})],
|
|
4916
|
+
`}};B([x({attribute:!1})],rA.prototype,`configResponse`,void 0),B([x({attribute:!1})],rA.prototype,`machineConfigResponse`,void 0),B([x({type:Boolean})],rA.prototype,`loading`,void 0),B([x({type:Boolean})],rA.prototype,`machineLoading`,void 0),B([x({type:Boolean})],rA.prototype,`saving`,void 0),B([x()],rA.prototype,`error`,void 0),B([x()],rA.prototype,`machineError`,void 0),B([x()],rA.prototype,`savedMessage`,void 0),B([x()],rA.prototype,`targetLabel`,void 0),B([x({attribute:!1})],rA.prototype,`onReload`,void 0),B([x({attribute:!1})],rA.prototype,`onReloadMachine`,void 0),B([x({attribute:!1})],rA.prototype,`onSave`,void 0),B([x({attribute:!1})],rA.prototype,`onSaveMachineConfig`,void 0),B([S()],rA.prototype,`gatewayDraft`,void 0),B([S()],rA.prototype,`machineDraft`,void 0),B([S()],rA.prototype,`gatewayLocalError`,void 0),B([S()],rA.prototype,`machineLocalError`,void 0),rA=B([b(`settings-general-panel`)],rA);function iA(e){return e===!0?`Any host`:Array.isArray(e)?e.length===0?g`<span class="muted">None listed</span>`:e.join(`, `):g`<span class="muted">Unset</span>`}function aA(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function oA(e){return e.target instanceof HTMLInputElement?e.target.value:``}function sA(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function cA(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function lA(e){return e instanceof Error?e.message:String(e)}function uA(e){return{spawnSessions:e}}function dA(e){return{subsessions:e}}function fA(e,t){let n=e?.effectiveConfig.agent;if(n?.command===void 0||n.dir===void 0||t===void 0)return`unavailable`;let r=[`PI_WEBUI_AGENT_SESSION_DIR`,...Pt(n.command)?[`PI_CODING_AGENT_SESSION_DIR`]:[]];return n.command===t.command&&n.dir===t.dir&&hA(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function pA(e,t){return e?.agentDirSource===`pi-webui`?!0:e?.agentDirSource===`pi-compatibility`?Pt(t.trim()||`pi`):e?.agentDir===!0}function mA(e,t){let n={...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions,agentCommand:t.envOverrides.agentCommand,agentDir:t.envOverrides.agentDir,agentSessionDir:t.envOverrides.agentSessionDir};return t.envOverrides.agentDirSource===void 0?delete n.agentDirSource:n.agentDirSource=t.envOverrides.agentDirSource,{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:n}}function hA(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var gA=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`,this.agentProfileSupport={state:`supported`},this.agentDraft=Hk(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=Hk(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||qk(this.agentDraft,this.configResponse.config))&&(this.agentDraft=Gk(this.configResponse.config),this.agentDraftDirty=!1,this.agentLocalError=``)}}render(){let e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,n=e?.effectiveConfig.spawnSessions!==!1,r=e?.envOverrides.subsessions===!0,i=e?.effectiveConfig.subsessions===!0&&n,a=e?.envOverrides.agentCommand===!0,o=this.agentProfileSupport.state===`supported`,s=a?e.effectiveConfig.agent?.command??this.agentDraft.command:this.agentDraft.command,c=pA(e?.envOverrides,s),l=e?.envOverrides.agentDir===!0,u=e?.effectiveConfig.agent,d=fA(e,this.activeAgentProfile);return g`
|
|
4915
4917
|
<settings-panel-frame
|
|
4916
4918
|
heading="Session daemon"
|
|
4917
|
-
.description=${
|
|
4919
|
+
.description=${bA(this.targetLabel)}
|
|
4918
4920
|
actionLabel="Reload"
|
|
4919
4921
|
.actionDisabled=${this.loading}
|
|
4920
4922
|
.notices=${this.panelNotices(e)}
|
|
@@ -4940,7 +4942,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4940
4942
|
.value=${this.agentDraft.command}
|
|
4941
4943
|
placeholder="pi"
|
|
4942
4944
|
?disabled=${this.loading||this.saving||!o||a}
|
|
4943
|
-
@input=${e=>{this.updateAgentDraft({command:
|
|
4945
|
+
@input=${e=>{this.updateAgentDraft({command:vA(e)})}}
|
|
4944
4946
|
>
|
|
4945
4947
|
<small>Set the Pi-compatible companion CLI used for doctor and update checks. The embedded session runtime remains PI WEBUI's bundled Pi SDK.</small>
|
|
4946
4948
|
</label>
|
|
@@ -4957,7 +4959,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4957
4959
|
.value=${this.agentDraft.dir}
|
|
4958
4960
|
placeholder="~/.pi/agent or ~/agent-profiles/work"
|
|
4959
4961
|
?disabled=${this.loading||this.saving||!o||c}
|
|
4960
|
-
@input=${e=>{this.updateAgentDraft({dir:
|
|
4962
|
+
@input=${e=>{this.updateAgentDraft({dir:vA(e)})}}
|
|
4961
4963
|
>
|
|
4962
4964
|
<small>Choose the Pi-compatible auth, models, settings, and sessions PI WEBUI reads. An alternate command and its required state directory are saved together.</small>
|
|
4963
4965
|
</label>
|
|
@@ -5005,14 +5007,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5005
5007
|
<div><dt>Desired state</dt><dd>${u?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
5006
5008
|
<div><dt>Active command</dt><dd>${this.activeAgentProfile?.command??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
5007
5009
|
<div><dt>Active state</dt><dd>${this.activeAgentProfile?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
5008
|
-
<div><dt>Profile status</dt><dd>${
|
|
5010
|
+
<div><dt>Profile status</dt><dd>${_A(d)}</dd></div>
|
|
5009
5011
|
<div><dt>Spawn sessions</dt><dd>${n?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
|
|
5010
5012
|
<div><dt>Subsessions</dt><dd>${i?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
|
|
5011
5013
|
</dl>
|
|
5012
5014
|
</section>
|
|
5013
5015
|
`}
|
|
5014
5016
|
</settings-panel-frame>
|
|
5015
|
-
`}panelNotices(e){return
|
|
5017
|
+
`}panelNotices(e){return xA(e,{error:this.agentLocalError||this.error,savedMessage:this.savedMessage,activeProfile:this.activeAgentProfile,targetLabel:this.targetLabel,profileEditingSupported:this.agentProfileSupport.state===`supported`})}renderUnavailableConfigState(){return g`<div class="loading-card">${this.loading?`Loading configuration…`:`Configuration is unavailable. Reload to try again.`}</div>`}async saveAgentProfile(e){e.preventDefault(),this.agentLocalError=``;try{await this.onSave?.(Kk(this.agentDraft))}catch(e){this.agentLocalError=yA(e)}}updateAgentDraft(e){this.agentDraft={...this.agentDraft,...e},this.agentDraftDirty=!0,this.agentLocalError=``}async toggleSpawnSessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(uA(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(dA(t))}static{this.styles=h`
|
|
5016
5018
|
:host { display: block; }
|
|
5017
5019
|
h3 { margin: 0; font-size: 13px; line-height: 1.3; }
|
|
5018
5020
|
button, input { font: inherit; }
|
|
@@ -5058,10 +5060,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5058
5060
|
@media (max-width: 760px) {
|
|
5059
5061
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
5060
5062
|
}
|
|
5061
|
-
`}};B([x({attribute:!1})],
|
|
5063
|
+
`}};B([x({attribute:!1})],gA.prototype,`configResponse`,void 0),B([x({type:Boolean})],gA.prototype,`loading`,void 0),B([x({type:Boolean})],gA.prototype,`saving`,void 0),B([x()],gA.prototype,`error`,void 0),B([x()],gA.prototype,`savedMessage`,void 0),B([x()],gA.prototype,`targetLabel`,void 0),B([x({attribute:!1})],gA.prototype,`activeAgentProfile`,void 0),B([x({attribute:!1})],gA.prototype,`agentProfileSupport`,void 0),B([x({attribute:!1})],gA.prototype,`onReload`,void 0),B([x({attribute:!1})],gA.prototype,`onSave`,void 0),B([S()],gA.prototype,`agentDraft`,void 0),B([S()],gA.prototype,`agentDraftDirty`,void 0),B([S()],gA.prototype,`agentLocalError`,void 0),gA=B([b(`settings-sessiond-panel`)],gA);function _A(e){return e===`active`?`Active`:e===`restart-required`?`Restart required`:g`<span class="muted">Unavailable</span>`}function vA(e){return e.target instanceof HTMLInputElement?e.target.value:``}function yA(e){return e instanceof Error?e.message:String(e)}function bA(e){return`Select the Pi-compatible agent profile and companion CLI for ${e}. Changes are saved immediately but only take effect after the session daemon on that machine restarts.`}function xA(e,t){let n=[];t.error!==``&&n.push({type:`error`,content:t.error}),t.savedMessage!==``&&n.push({type:`success`,content:t.savedMessage});let r=fA(e,t.activeProfile);return r===`restart-required`?n.push({type:`warning`,title:`Pi-compatible agent profile restart required on ${t.targetLabel}`,content:g`The desired profile differs from the active session-daemon profile. Run <code>pi-webui restart</code> on that machine (or restart its session daemon service) to apply the command and state directory together.`}):e!==void 0&&r===`unavailable`&&t.profileEditingSupported&&n.push({type:`info`,title:`Active Pi-compatible agent profile unavailable on ${t.targetLabel}`,content:`PI WEBUI cannot compare the desired profile with the running session daemon. Reload after the daemon is available.`}),n}function SA(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function CA(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function wA(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?E(t,w.piPackagesManage)?{state:`supported`}:{state:`unsupported`,message:DA(e)}:{state:`unknown`}}function TA(e){return`${e.state}:${e.message??``}`}function EA(e){return e?.state===`unsupported`}function DA(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function OA(e){return e.kind===`local`}function kA(e){return e.trim()}function AA(e){if(kA(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function jA(e){return e.scope===`project`?`Project scope`:`User scope`}function MA(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEBUI process`}function NA(e){return e.installedPath??`Installed path not reported by Pi`}function PA(e){return e.scope===`user`}function FA(e){if(!PA(e))return`Project-scope Pi packages are listed for visibility, but PI WEBUI only updates user-scope Pi packages safely from this view.`}function IA(e){return e.length>0&&e.every(PA)}function LA(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!IA(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function RA(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function zA(e,t=SA(void 0)){return`Pi package ${e===`install`?`installed`:e===`remove`?`removed`:`updated`}${t.kind===`local`?``:` on ${t.name}`}. Type /reload in ${t.kind===`local`?`each idle PI WEBUI session`:`each idle PI WEBUI session on ${t.name}`} to rediscover Pi runtime resources: extensions, skills, prompt templates, themes, and context/system prompt files. Reload the browser page separately for ${t.kind===`local`?`PI WEBUI browser plugin changes`:`PI WEBUI browser plugin changes served by ${t.name}`}.`}function BA(e,t){let n=e.trim();return t.kind===`remote`?VA(n)?DA(t):n===`Remote machine timeout`?`Timed out while contacting ${t.name} for Pi package management. The package operation may still be running remotely; reload the package list before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for Pi package management. Check the machine connection and try again.`:n:n}function VA(e){return e===`Not Found`||/route\s+(GET|POST):?\/api\/pi-packages\b.*not found/iu.test(e)||/cannot\s+(GET|POST)\s+.*\/api\/pi-packages\b/iu.test(e)}var HA=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.operationMessage=``,this.installSource=``,this.validationMessage=``}render(){let e=this.packagesResponse?.packages??[],t=this.packageTarget,n=CA(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
|
|
5062
5064
|
<settings-panel-frame
|
|
5063
5065
|
heading="Pi packages"
|
|
5064
|
-
.description=${
|
|
5066
|
+
.description=${UA(n)}
|
|
5065
5067
|
actionLabel="Reload"
|
|
5066
5068
|
actionTitle=${r?this.packageManagementUnavailableMessage(n):`Reload Pi packages from ${n}`}
|
|
5067
5069
|
.actionDisabled=${this.loading||this.isOperating||r}
|
|
@@ -5078,12 +5080,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5078
5080
|
<label for="package-source">Pi package source</label>
|
|
5079
5081
|
<div class="install-row">
|
|
5080
5082
|
<input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package, git URL, or local path" @input=${e=>{this.updateInstallSource(e)}}>
|
|
5081
|
-
<button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${
|
|
5083
|
+
<button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${RA(this.operation,`install`)?`Installing…`:`Install`}</button>
|
|
5082
5084
|
</div>
|
|
5083
5085
|
${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
|
|
5084
5086
|
<small>Installs run on ${e} and use Pi's default package location, equivalent to <code>pi install <source></code>. PI WEBUI does not ask you to choose an install location.</small>
|
|
5085
5087
|
</form>
|
|
5086
|
-
`}renderPackageList(e,t){let n=
|
|
5088
|
+
`}renderPackageList(e,t){let n=CA(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):LA(e),i=r!==void 0&&e.length>0;return g`
|
|
5087
5089
|
<section class="package-section" aria-label="Configured Pi packages">
|
|
5088
5090
|
<div class="package-toolbar">
|
|
5089
5091
|
<div>
|
|
@@ -5091,7 +5093,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5091
5093
|
<p>This list comes from Pi's package manager settings on ${n}.</p>
|
|
5092
5094
|
</div>
|
|
5093
5095
|
<button class="secondary" title=${r??`Update all user-scope Pi packages`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
|
|
5094
|
-
${
|
|
5096
|
+
${RA(this.operation,`update-all`)?`Updating…`:`Update all`}
|
|
5095
5097
|
</button>
|
|
5096
5098
|
</div>
|
|
5097
5099
|
${i?g`<div class="action-note">${r}</div>`:null}
|
|
@@ -5102,12 +5104,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5102
5104
|
<div class="package-list">
|
|
5103
5105
|
${e.map(e=>this.renderPackage(e))}
|
|
5104
5106
|
</div>
|
|
5105
|
-
`}renderPackage(e){let t=
|
|
5107
|
+
`}renderPackage(e){let t=CA(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):FA(e),i=n?this.packageManagementUnavailableMessage(t):`Remove this Pi package`,a=RA(this.operation,`update`,e.source),o=RA(this.operation,`remove`,e.source);return g`
|
|
5106
5108
|
<article class=${`package-card${e.filtered?` filtered`:``}`}>
|
|
5107
5109
|
<div class="package-main">
|
|
5108
5110
|
<strong>${e.source}</strong>
|
|
5109
|
-
<small>${
|
|
5110
|
-
<small>Installed path: <code>${
|
|
5111
|
+
<small>${jA(e)} · ${MA(e)}</small>
|
|
5112
|
+
<small>Installed path: <code>${NA(e)}</code></small>
|
|
5111
5113
|
${r===void 0?null:g`<small class="action-note">${r}</small>`}
|
|
5112
5114
|
</div>
|
|
5113
5115
|
<div class="package-actions">
|
|
@@ -5115,7 +5117,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5115
5117
|
<button class="danger" title=${i} ?disabled=${this.isOperating||n} @click=${()=>{this.removePackage(e)}}>${o?`Removing…`:`Remove`}</button>
|
|
5116
5118
|
</div>
|
|
5117
5119
|
</article>
|
|
5118
|
-
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=
|
|
5120
|
+
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=AA(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=kA(this.installSource);try{await this.onInstallPackage?.(n),this.installSource=``,this.validationMessage=``}catch{}}async removePackage(e){try{await this.onRemovePackage?.(e.source,e.scope)}catch{}}async updatePackage(e){try{await this.onUpdatePackage?.(e)}catch{}}get packageTarget(){return this.targetMachine??SA(void 0)}get packageManagementUnavailable(){return EA(this.managementSupport)}packageManagementUnavailableMessage(e){return this.managementSupport?.message??`Pi package management is not available on ${e}.`}get isOperating(){return this.operation!==void 0}static{this.styles=h`
|
|
5119
5121
|
:host { display: block; }
|
|
5120
5122
|
.package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
5121
5123
|
.package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -5150,10 +5152,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5150
5152
|
.package-actions { justify-self: start; flex-wrap: wrap; }
|
|
5151
5153
|
.package-main strong, .package-main small { white-space: normal; }
|
|
5152
5154
|
}
|
|
5153
|
-
`}};B([x({attribute:!1})],
|
|
5155
|
+
`}};B([x({attribute:!1})],HA.prototype,`packagesResponse`,void 0),B([x({type:Boolean})],HA.prototype,`loading`,void 0),B([x({attribute:!1})],HA.prototype,`operation`,void 0),B([x({attribute:!1})],HA.prototype,`targetMachine`,void 0),B([x({attribute:!1})],HA.prototype,`managementSupport`,void 0),B([x()],HA.prototype,`error`,void 0),B([x()],HA.prototype,`operationMessage`,void 0),B([x({attribute:!1})],HA.prototype,`onReload`,void 0),B([x({attribute:!1})],HA.prototype,`onInstallPackage`,void 0),B([x({attribute:!1})],HA.prototype,`onRemovePackage`,void 0),B([x({attribute:!1})],HA.prototype,`onUpdatePackage`,void 0),B([S()],HA.prototype,`installSource`,void 0),B([S()],HA.prototype,`validationMessage`,void 0),HA=B([b(`settings-packages-panel`)],HA);function UA(e){return g`Managing Pi packages on <strong>${e}</strong>. Install, remove, and update packages managed by Pi on the selected machine. Pi packages can provide extensions, skills, prompt templates, themes, context/system prompt files, and PI WEBUI browser plugins.`}var WA=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}render(){let e=this.pluginsResponse?.plugins??[],t=this.pluginsResponse!==void 0;return g`
|
|
5154
5156
|
<settings-panel-frame
|
|
5155
5157
|
heading="PI WEBUI plugins"
|
|
5156
|
-
.description=${
|
|
5158
|
+
.description=${GA(this.targetLabel)}
|
|
5157
5159
|
actionLabel="Reload"
|
|
5158
5160
|
actionTitle=${`Reload PI WEBUI plugins from ${this.targetLabel}`}
|
|
5159
5161
|
.actionDisabled=${this.loading}
|
|
@@ -5199,7 +5201,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5199
5201
|
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
5200
5202
|
.toggle { justify-self: start; }
|
|
5201
5203
|
}
|
|
5202
|
-
`}};B([x({attribute:!1})],
|
|
5204
|
+
`}};B([x({attribute:!1})],WA.prototype,`pluginsResponse`,void 0),B([x({attribute:!1})],WA.prototype,`configResponse`,void 0),B([x({type:Boolean})],WA.prototype,`loading`,void 0),B([x({type:Boolean})],WA.prototype,`saving`,void 0),B([x()],WA.prototype,`error`,void 0),B([x()],WA.prototype,`savedMessage`,void 0),B([x()],WA.prototype,`targetLabel`,void 0),B([x({attribute:!1})],WA.prototype,`onReload`,void 0),B([x({attribute:!1})],WA.prototype,`onTogglePlugin`,void 0),WA=B([b(`settings-plugins-panel`)],WA);function GA(e){return g`Enable or disable discovered PI WEBUI browser plugins on <strong>${e}</strong>. This is separate from installing Pi packages. Reload the browser tab to apply plugin runtime changes.`}function KA(e){return JSON.stringify([e.provider,e.id])}function qA(e){return`${e.provider}/${e.id}`}function JA(e,t){return e.find(e=>KA(e.model)===t)}function YA(e,t){let n=[...e].sort((e,t)=>e.model.provider===t.model.provider?e.model.id.localeCompare(t.model.id):e.model.provider.localeCompare(t.model.provider)).map(e=>({value:KA(e.model),label:e.model.id,...e.name===void 0||e.name===``||e.name===e.model.id?{}:{description:e.name},...e.model.provider===``?{}:{group:e.model.provider}}));return t===void 0?n:[{value:``,label:t.label},...n]}var XA=class extends y{constructor(...e){super(...e),this.triggerId=``,this.accessibleLabel=``,this.dialogTitle=`Select Model`,this.choices=[],this.inheritedLabel=``,this.placeholder=`Select a model…`,this.disabled=!1,this.invalid=!1,this.pickerOpen=!1}get isPickerOpen(){return this.pickerOpen}render(){let e=this.selected,t=e!==void 0&&this.choices.some(t=>ZA(t.model,e)),n=e===void 0?this.emptyLabel():`${qA(e)}${t?``:` (unavailable)`}`;return g`
|
|
5203
5205
|
<button
|
|
5204
5206
|
type="button"
|
|
5205
5207
|
id=${this.triggerId}
|
|
@@ -5216,7 +5218,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5216
5218
|
<span class="model-chevron" aria-hidden="true">▾</span>
|
|
5217
5219
|
</button>
|
|
5218
5220
|
${this.pickerOpen?this.renderPicker():null}
|
|
5219
|
-
`}renderPicker(){let e=this.selected,t=
|
|
5221
|
+
`}renderPicker(){let e=this.selected,t=YA(this.choices,this.inheritedLabel===``?void 0:{label:this.inheritedLabel}),n=e===void 0?this.inheritedLabel===``?void 0:``:KA(e);return g`
|
|
5220
5222
|
<div
|
|
5221
5223
|
class="picker-host"
|
|
5222
5224
|
@keydown=${e=>{e.key===`Escape`&&e.stopPropagation()}}
|
|
@@ -5231,7 +5233,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5231
5233
|
.onCancel=${()=>{this.closePicker()}}
|
|
5232
5234
|
></command-picker>
|
|
5233
5235
|
</div>
|
|
5234
|
-
`}showPicker(){this.disabled||(this.pickerOpen=!0)}closePicker(){this.pickerOpen&&(this.pickerOpen=!1,this.updateComplete.then(()=>{this.isConnected&&this.renderRoot.querySelector(`.model-trigger`)?.focus()}))}pickModel(e){if(e===``){if(this.inheritedLabel===``)return;this.closePicker(),this.onSelect?.(void 0);return}let t=
|
|
5236
|
+
`}showPicker(){this.disabled||(this.pickerOpen=!0)}closePicker(){this.pickerOpen&&(this.pickerOpen=!1,this.updateComplete.then(()=>{this.isConnected&&this.renderRoot.querySelector(`.model-trigger`)?.focus()}))}pickModel(e){if(e===``){if(this.inheritedLabel===``)return;this.closePicker(),this.onSelect?.(void 0);return}let t=JA(this.choices,e);t!==void 0&&(this.closePicker(),this.onSelect?.({...t.model}))}emptyLabel(){return this.inheritedLabel===``?this.placeholder:this.inheritedLabel}triggerTitle(e,t){let n=this.selected;if(n===void 0||!t)return e;let r=this.choices.find(e=>ZA(e.model,n))?.name;return r===void 0||r===``||r===n.id?e:`${r} (${e})`}static{this.styles=h`
|
|
5235
5237
|
:host { display: block; min-width: 0; }
|
|
5236
5238
|
.model-trigger { display: flex; align-items: center; justify-content: space-between; gap: 8px; width: 100%; min-width: 0; box-sizing: border-box; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 7px 10px; font: inherit; font-size: 13px; text-align: left; cursor: pointer; }
|
|
5237
5239
|
.model-trigger:hover:not(:disabled), .model-trigger:focus-visible { border-color: var(--pi-accent); }
|
|
@@ -5240,7 +5242,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5240
5242
|
.model-trigger.empty .model-summary { color: var(--pi-muted); }
|
|
5241
5243
|
.model-summary { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
5242
5244
|
.model-chevron { flex: 0 0 auto; color: var(--pi-muted); }
|
|
5243
|
-
`}};B([x()],
|
|
5245
|
+
`}};B([x()],XA.prototype,`triggerId`,void 0),B([x()],XA.prototype,`accessibleLabel`,void 0),B([x()],XA.prototype,`dialogTitle`,void 0),B([x({attribute:!1})],XA.prototype,`choices`,void 0),B([x({attribute:!1})],XA.prototype,`selected`,void 0),B([x()],XA.prototype,`inheritedLabel`,void 0),B([x()],XA.prototype,`placeholder`,void 0),B([x({type:Boolean})],XA.prototype,`disabled`,void 0),B([x({type:Boolean})],XA.prototype,`invalid`,void 0),B([x({attribute:!1})],XA.prototype,`onSelect`,void 0),B([S()],XA.prototype,`pickerOpen`,void 0),XA=B([b(`settings-model-picker-field`)],XA);function ZA(e,t){return e.provider===t.provider&&e.id===t.id}function QA(){return{economy:ij(),fast:ij(),standard:ij(),advanced:ij(),capable:ij(),frontier:ij()}}function $A(e){return e.ladder===void 0?QA():{economy:aj(e.ladder.economy),fast:aj(e.ladder.fast),standard:aj(e.ladder.standard),advanced:aj(e.ladder.advanced),capable:aj(e.ladder.capable),frontier:aj(e.ladder.frontier)}}function ej(e,t,n){let r=e[t],i=r.thinkingLevel===``||n.thinkingLevels.includes(r.thinkingLevel)?r.thinkingLevel:``;return{...e,[t]:{model:{...n.model},thinkingLevel:i}}}function tj(e,t,n){return{...e,[t]:{...e[t],thinkingLevel:n}}}function nj(e,t){let n={economy:sj(`economy`,e.economy,t),fast:sj(`fast`,e.fast,t),standard:sj(`standard`,e.standard,t),advanced:sj(`advanced`,e.advanced,t),capable:sj(`capable`,e.capable,t),frontier:sj(`frontier`,e.frontier,t)};return{valid:bt.every(e=>n[e].valid),rows:n}}function rj(e,t){if(nj(e,t).valid)return{economy:oj(e.economy),fast:oj(e.fast),standard:oj(e.standard),advanced:oj(e.advanced),capable:oj(e.capable),frontier:oj(e.frontier)}}function ij(){return{thinkingLevel:``}}function aj(e){return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function oj(e){if(e.model===void 0)throw Error(`Cannot build a model-tier ladder from an incomplete draft`);return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function sj(e,t,n){let r=t.model;if(r===void 0)return{valid:!1,reason:`tier ${e} has no model selected`};let i=n.find(e=>cj(e.model,r));return i===void 0?{valid:!1,reason:`tier ${e} names unavailable model ${lj(r)}`}:t.thinkingLevel===``?{valid:!1,reason:`tier ${e} has no thinking level selected`}:i.thinkingLevels.includes(t.thinkingLevel)?{valid:!0}:{valid:!1,reason:`tier ${e} names thinking level ${t.thinkingLevel}, unsupported by ${lj(r)}`}}function cj(e,t){return e.provider===t.provider&&e.id===t.id}function lj(e){return`${e.provider}/${e.id}`}var uj={economy:{label:`Economy`,step:`1`},fast:{label:`Fast`,step:`↓`},standard:{label:`Standard`,step:`↓`},advanced:{label:`Advanced`,step:`↓`},capable:{label:`Capable`,step:`↓`},frontier:{label:`Frontier`,step:`6`}},dj=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.support={state:`supported`},this.draft=QA()}get canSave(){let e=this.response?.models??[];return nj(this.draft,e).valid&&!this.saving&&!this.loading&&this.support.state===`supported`}willUpdate(e){e.has(`response`)&&(this.response===void 0?this.draft=QA():this.draft=$A(this.response))}handleReload(){this.onReload?.()}handleSave(){if(!this.canSave)return;let e=this.response?.models??[],t=rj(this.draft,e);t&&this.onSave&&this.onSave(t)}handleModelChange(e,t){this.draft=ej(this.draft,e,t)}handleThinkingChange(e,t){this.draft=tj(this.draft,e,t)}onModelPicked(e,t){if(t===void 0)return;let n=(this.response?.models??[]).find(e=>fj(e.model,t));n!==void 0&&this.handleModelChange(e,n)}onThinkingSelectChange(e,t){t.target instanceof HTMLSelectElement&&this.handleThinkingChange(e,t.target.value)}panelNotices(){let e=[];return this.support.state===`unsupported`?e.push({type:`availability`,tone:`error`,content:this.support.message??`Model tier configuration is not available on ${this.targetLabel}. Update and restart Pi-Web on that machine, then try again.`}):this.support.state===`unknown`&&e.push({type:`availability`,tone:`warning`,content:this.support.message??`Model tier configuration support is unknown for ${this.targetLabel}.`}),this.error!==``&&e.push({type:`error`,content:this.error}),this.response?.configError!==void 0&&this.response.configError!==``&&e.push({type:`error`,title:`Configuration error`,content:this.response.configError}),this.savedMessage!==``&&e.push({type:`success`,content:this.savedMessage}),e}render(){let e=this.response?.models??[],t=nj(this.draft,e),n=bt.filter(e=>t.rows[e].valid).length,r=this.loading||this.saving||this.support.state!==`supported`;return g`
|
|
5244
5246
|
<settings-panel-frame
|
|
5245
5247
|
heading="Model tiers"
|
|
5246
5248
|
description="Configure the six exact model/thinking bindings used by tiered sessions."
|
|
@@ -5274,7 +5276,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5274
5276
|
</footer>
|
|
5275
5277
|
`}
|
|
5276
5278
|
</settings-panel-frame>
|
|
5277
|
-
`}renderTierRow(e,t,n,r){let i=
|
|
5279
|
+
`}renderTierRow(e,t,n,r){let i=uj[e],a=this.draft[e],o=n.rows[e],s=a.model,c=s?t.find(e=>fj(e.model,s)):void 0;return g`
|
|
5278
5280
|
<div class="tier-row ${o.valid?``:`invalid`}" data-tier=${e}>
|
|
5279
5281
|
<div class="step-col" aria-hidden="true">${i.step}</div>
|
|
5280
5282
|
<div class="tier-col">
|
|
@@ -5486,10 +5488,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5486
5488
|
width: 100%;
|
|
5487
5489
|
}
|
|
5488
5490
|
}
|
|
5489
|
-
`}};B([x({attribute:!1})],
|
|
5491
|
+
`}};B([x({attribute:!1})],dj.prototype,`response`,void 0),B([x({type:Boolean})],dj.prototype,`loading`,void 0),B([x({type:Boolean})],dj.prototype,`saving`,void 0),B([x()],dj.prototype,`error`,void 0),B([x()],dj.prototype,`savedMessage`,void 0),B([x()],dj.prototype,`targetLabel`,void 0),B([x({attribute:!1})],dj.prototype,`support`,void 0),B([x({attribute:!1})],dj.prototype,`onReload`,void 0),B([x({attribute:!1})],dj.prototype,`onSave`,void 0),B([S()],dj.prototype,`draft`,void 0),dj=B([b(`settings-model-tiers-panel`)],dj);function fj(e,t){return e.provider===t.provider&&e.id===t.id}var pj={capture:!0},mj=[{value:`auto`,label:`Auto/default`,description:`Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line.`},{value:`send`,label:`Enter sends message`,description:`Enter sends the chat message; Shift+Enter adds a new line when supported.`},{value:`newline`,label:`Enter inserts new line`,description:`Enter adds a line break; Shift+Enter sends the chat message when supported.`}];function hj(){return g`Edit app shortcuts by action. Type a shortcut such as <code>mod+k</code> or <code>mod+g p</code>, record one from the keyboard, disable it with None, or reset it to the default. When shortcuts conflict, custom shortcuts win before defaults; ties are resolved by action id, and shorter shortcuts shadow longer sequences with the same prefix.`}var gj=class extends y{constructor(...e){super(...e),this.actions=[],this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.drafts={},this.localError=``,this.promptEnterPreference=sD(),this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{let t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key===`Escape`){this.stopRecording();return}let n=rh(e);if(n===void 0){this.localError=`Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.`;return}if(t.tokens.length===0&&!ih(n)){this.localError=`Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.`;return}let r=[...t.tokens,n];this.localError=``,this.drafts={[t.actionId]:r.join(` `)},this.recording={actionId:t.actionId,tokens:r},this.armRecordingTimer()}}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.drafts={},this.localError=``,this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){let e=bj(this.actions),t=this.shortcutResolutions();return g`
|
|
5490
5492
|
<settings-panel-frame
|
|
5491
5493
|
heading="Keyboard shortcuts"
|
|
5492
|
-
.description=${
|
|
5494
|
+
.description=${hj()}
|
|
5493
5495
|
actionLabel="Reload"
|
|
5494
5496
|
.actionDisabled=${this.loading}
|
|
5495
5497
|
.notices=${this.panelNotices()}
|
|
@@ -5520,7 +5522,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5520
5522
|
<p>Choose what Enter does in this browser. Shift+Enter does the opposite when supported; automatic touch-keyboard capitalization is ignored to avoid accidental sends.</p>
|
|
5521
5523
|
</div>
|
|
5522
5524
|
<div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
|
|
5523
|
-
${
|
|
5525
|
+
${mj.map(e=>g`
|
|
5524
5526
|
<label class="prompt-enter-option">
|
|
5525
5527
|
<input
|
|
5526
5528
|
type="radio"
|
|
@@ -5537,8 +5539,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5537
5539
|
`)}
|
|
5538
5540
|
</div>
|
|
5539
5541
|
</section>
|
|
5540
|
-
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,
|
|
5541
|
-
<article class=${
|
|
5542
|
+
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,cD(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=Sj(e.id,n),i=Tj(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:eh(a),s=o?.ok===!0?o.shortcut:wj(e,n),c=r!==void 0,l=this.drafts[e.id]!==void 0,u=l&&a.trim()!==``?`custom`:i,d=this.recordingHint(e.id),f=yj(t);return g`
|
|
5543
|
+
<article class=${_j(t)}>
|
|
5542
5544
|
<div class="shortcut-main">
|
|
5543
5545
|
<strong>${e.title}</strong>
|
|
5544
5546
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -5548,8 +5550,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5548
5550
|
<div class="shortcut-editor">
|
|
5549
5551
|
<div class="shortcut-status">
|
|
5550
5552
|
${s!==void 0&&s!==``?g`<kbd>${nh(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`Disabled`:`Unassigned`}</span>`}
|
|
5551
|
-
<small class=${u}>${
|
|
5552
|
-
${f===void 0?null:g`<small class=${
|
|
5553
|
+
<small class=${u}>${Ej(u)}${l?` · Unsaved`:``}</small>
|
|
5554
|
+
${f===void 0?null:g`<small class=${vj(t)}>${f}</small>`}
|
|
5553
5555
|
</div>
|
|
5554
5556
|
<label class="shortcut-input-label">
|
|
5555
5557
|
<span>Shortcut</span>
|
|
@@ -5562,7 +5564,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5562
5564
|
autocapitalize="off"
|
|
5563
5565
|
spellcheck="false"
|
|
5564
5566
|
?disabled=${this.saving}
|
|
5565
|
-
@input=${t=>{this.updateDraft(e.id,
|
|
5567
|
+
@input=${t=>{this.updateDraft(e.id,Dj(t))}}
|
|
5566
5568
|
>
|
|
5567
5569
|
</label>
|
|
5568
5570
|
${d===``?null:g`<small class="recording-hint">${d}</small>`}
|
|
@@ -5574,7 +5576,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5574
5576
|
</div>
|
|
5575
5577
|
</div>
|
|
5576
5578
|
</article>
|
|
5577
|
-
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=
|
|
5579
|
+
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=Sj(e.id,this.configResponse?.config.shortcuts);return n===null?``:n??e.shortcut??``}recordingHint(e){let t=this.recording;return t?.actionId===e?t.tokens.length===0?`Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.`:`Recording: ${nh(t.tokens.join(` `))}. Press another key to add a sequence, or wait to finish.`:``}updateDraft(e,t){this.drafts={[e]:t},this.localError=``}async saveShortcut(e){this.stopRecording();let t=eh(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e.id,t.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError=``,await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError=``,await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){let n={...this.configResponse?.config??{}},r=n.shortcuts??{},i=t===void 0?Cj(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map($m(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){let e={...this.configResponse?.config.shortcuts??{}};for(let[t,n]of Object.entries(this.drafts)){let r=n.trim();if(r===``)continue;let i=eh(r);i.ok&&(e[t]=i.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError=``,this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(let t of this.renderRoot.querySelectorAll(`.shortcut-input`))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},Xm)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||=(window.addEventListener(`keydown`,this.onRecordKeyDown,pj),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,pj),!1)}static{this.styles=h`
|
|
5578
5580
|
:host { display: block; }
|
|
5579
5581
|
h3, p { margin: 0; }
|
|
5580
5582
|
h3 { font-size: 13px; line-height: 1.3; }
|
|
@@ -5630,7 +5632,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5630
5632
|
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
5631
5633
|
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
5632
5634
|
}
|
|
5633
|
-
`}};B([x({attribute:!1})],
|
|
5635
|
+
`}};B([x({attribute:!1})],gj.prototype,`actions`,void 0),B([x({attribute:!1})],gj.prototype,`configResponse`,void 0),B([x({type:Boolean})],gj.prototype,`loading`,void 0),B([x({type:Boolean})],gj.prototype,`saving`,void 0),B([x()],gj.prototype,`error`,void 0),B([x()],gj.prototype,`savedMessage`,void 0),B([x({attribute:!1})],gj.prototype,`onReload`,void 0),B([x({attribute:!1})],gj.prototype,`onSave`,void 0),B([S()],gj.prototype,`drafts`,void 0),B([S()],gj.prototype,`localError`,void 0),B([S()],gj.prototype,`promptEnterPreference`,void 0),B([S()],gj.prototype,`recording`,void 0),gj=B([b(`settings-shortcuts-panel`)],gj);function _j(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function vj(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function yj(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??`another action`}`;let t=e.shadows.length;if(t===0)return;let n=e.shadows.slice(0,2).map(e=>e.action.title).join(`, `),r=t>2?`, +${String(t-2)} more`:``;return`Shadows ${String(t)} ${t===1?`action`:`actions`}: ${n}${r}`}function bj(e){let t=new Map;for(let n of[...e].sort(xj)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function xj(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function Sj(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Cj(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function wj(e,t){let n=Sj(e.id,t);if(n!==null)return n??e.shortcut}function Tj(e,t){let n=Sj(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function Ej(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function Dj(e){return e.target instanceof HTMLInputElement?e.target.value:``}var Oj=`auto`;function kj(e){return Ij(e.settings)}function Aj(e,t,n){return Lj(e,t,n===void 0?void 0:n.model)}function jj(e,t,n){let r=e[t];return r===void 0||n!==`auto`&&!Xt(n)?Ij(e):Lj(e,t,n===`auto`?{provider:r.provider,id:r.id}:{provider:r.provider,id:r.id,thinkingLevel:n})}function Mj(e,t){let n=Fj();if(e.contractVersion!==2||t===void 0)return[n];let r=e.models.find(e=>Hj(e.model,t));if(r===void 0)return[n];let i=new Set(r.thinkingLevels),a=Yt.filter(e=>i.has(e)),o=[n];return t.thinkingLevel!==void 0&&!i.has(t.thinkingLevel)&&o.push({value:t.thinkingLevel,label:`${t.thinkingLevel} (unavailable)`,disabled:!0}),o.push(...a.map(e=>({value:e,label:e,disabled:!1}))),o}function Nj(e,t){let n={lightweight:Bj(`lightweight`,e.lightweight,t),context:Bj(`context`,e.context,t)};return{valid:n.lightweight.valid&&n.context.valid,slots:n}}function Pj(e,t){if(Nj(e,t).valid)return{lightweight:e.lightweight===void 0?null:zj(e.lightweight),context:e.context===void 0?null:zj(e.context)}}function Fj(){return{value:Oj,label:Oj,disabled:!1}}function Ij(e){return Rj(e.lightweight,e.context)}function Lj(e,t,n){return Rj(t===`lightweight`?n:e.lightweight,t===`context`?n:e.context)}function Rj(e,t){return{...e===void 0?{}:{lightweight:zj(e)},...t===void 0?{}:{context:zj(t)}}}function zj(e){return{provider:e.provider,id:e.id,...e.thinkingLevel===void 0?{}:{thinkingLevel:e.thinkingLevel}}}function Bj(e,t,n){if(t===void 0)return{valid:!0};let r=n.models.find(e=>Hj(e.model,t));return r===void 0?{valid:!1,reason:`utility slot ${e} names unavailable model ${Uj(t)}`}:t.thinkingLevel===void 0?{valid:!0}:n.contractVersion===2?!Xt(t.thinkingLevel)||!Vj(r,t.thinkingLevel)?{valid:!1,reason:`utility slot ${e} names thinking level ${t.thinkingLevel}, unsupported by ${Uj(t)}`}:{valid:!0}:{valid:!1,reason:`utility slot ${e} names thinking level ${t.thinkingLevel}, unavailable in this runtime`}}function Vj(e,t){return`thinkingLevels`in e&&e.thinkingLevels.includes(t)}function Hj(e,t){return e.provider===t.provider&&e.id===t.id}function Uj(e){return`${e.provider}/${e.id}`}var Wj={lightweight:{label:`Lightweight`,description:`Titles and branch summaries`,emptyLabel:`Use active session model`},context:{label:`Context`,description:`Compaction and context summaries`,emptyLabel:`Use lightweight, then active session model`}},Gj=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.support={state:`supported`},this.draft={}}get editingDisabled(){return this.loading||this.saving||this.support.state!==`supported`}get canSave(){return this.response!==void 0&&Nj(this.draft,this.response).valid&&!this.editingDisabled}willUpdate(e){e.has(`response`)&&(this.draft=this.response===void 0?{}:kj(this.response))}handleReload(){this.onReload?.()}handleSave(){let e=this.response;if(!this.canSave||e===void 0)return;let t=Pj(this.draft,e);t!==void 0&&this.onSave!==void 0&&this.onSave(t)}handleModelChange(e,t){this.draft=Aj(this.draft,e,t)}handleThinkingChange(e,t){this.draft=jj(this.draft,e,t)}panelNotices(){let e=[];return this.support.state===`unsupported`?e.push({type:`availability`,tone:`error`,content:this.support.message??`Utility model settings are not available on ${this.targetLabel}. Update and restart PI WEBUI on that machine, then try again.`}):this.support.state===`unknown`&&e.push({type:`availability`,tone:`warning`,content:this.support.message??`Utility model settings support is unknown for ${this.targetLabel}.`}),this.response?.contractVersion===1&&e.push({type:`info`,content:`Explicit thinking levels require a newer PI WEBUI runtime on ${this.targetLabel}. Model routing remains available.`}),this.error!==``&&e.push({type:`error`,content:this.error}),this.response?.configError!==void 0&&this.response.configError!==``&&e.push({type:`error`,title:`Configuration error`,content:this.response.configError}),this.savedMessage!==``&&e.push({type:`success`,content:this.savedMessage}),e}render(){return g`
|
|
5634
5636
|
<settings-panel-frame
|
|
5635
5637
|
heading="Utility models"
|
|
5636
5638
|
description="Choose machine-global models for utility operations outside active sessions."
|
|
@@ -5661,7 +5663,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5661
5663
|
</footer>
|
|
5662
5664
|
`}
|
|
5663
5665
|
</settings-panel-frame>
|
|
5664
|
-
`}renderFieldRow(e){let t=this.response;if(t===void 0)return g``;let n=
|
|
5666
|
+
`}renderFieldRow(e){let t=this.response;if(t===void 0)return g``;let n=Wj[e],r=this.draft[e],i=r===void 0?void 0:t.models.find(e=>Kj(e.model,r)),a=Nj(this.draft,t).slots[e],o=`select-utility-model-${e}`,s=`select-utility-thinking-${e}`,c=Mj(t,r),l=t.contractVersion===2&&i!==void 0?r?.thinkingLevel??`auto`:Oj,u=this.editingDisabled||t.contractVersion===1||r===void 0||i===void 0;return g`
|
|
5665
5667
|
<div class="field-row ${a.valid?``:`invalid`}" data-slot=${e}>
|
|
5666
5668
|
<div class="field-copy">
|
|
5667
5669
|
<span class="slot-label">${n.label}</span>
|
|
@@ -5703,7 +5705,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5703
5705
|
</div>
|
|
5704
5706
|
${!a.valid&&a.reason!==void 0&&a.reason!==``?g`<div class="row-error" role="alert">${a.reason}</div>`:null}
|
|
5705
5707
|
</div>
|
|
5706
|
-
`}onModelLabelClick(e){if(!(e.currentTarget instanceof HTMLElement))return;let t=e.currentTarget.nextElementSibling;t instanceof
|
|
5708
|
+
`}onModelLabelClick(e){if(!(e.currentTarget instanceof HTMLElement))return;let t=e.currentTarget.nextElementSibling;t instanceof XA&&t.showPicker()}onModelPicked(e,t){if(t===void 0){this.handleModelChange(e,void 0);return}let n=this.response?.models.find(e=>Kj(e.model,t));n!==void 0&&this.handleModelChange(e,n)}onThinkingSelectChange(e,t){if(!(t.target instanceof HTMLSelectElement))return;let n=t.target.value;n!==`auto`&&!Xt(n)||this.handleThinkingChange(e,n)}static{this.styles=h`
|
|
5707
5709
|
:host { display: block; }
|
|
5708
5710
|
.loading-message { color: var(--pi-muted); }
|
|
5709
5711
|
.field-list { display: grid; gap: 14px; }
|
|
@@ -5729,7 +5731,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5729
5731
|
.panel-footer { display: block; }
|
|
5730
5732
|
button.primary { width: 100%; }
|
|
5731
5733
|
}
|
|
5732
|
-
`}};B([x({attribute:!1})],
|
|
5734
|
+
`}};B([x({attribute:!1})],Gj.prototype,`response`,void 0),B([x({type:Boolean})],Gj.prototype,`loading`,void 0),B([x({type:Boolean})],Gj.prototype,`saving`,void 0),B([x()],Gj.prototype,`error`,void 0),B([x()],Gj.prototype,`savedMessage`,void 0),B([x()],Gj.prototype,`targetLabel`,void 0),B([x({attribute:!1})],Gj.prototype,`support`,void 0),B([x({attribute:!1})],Gj.prototype,`onReload`,void 0),B([x({attribute:!1})],Gj.prototype,`onSave`,void 0),B([S()],Gj.prototype,`draft`,void 0),Gj=B([b(`settings-utility-models-panel`)],Gj);function Kj(e,t){return e.provider===t.provider&&e.id===t.id}async function qj(e){let[t,n]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),r={error:``},i=[];return t.status===`fulfilled`?r.config=t.value:i.push(`config: ${Yj(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEBUI plugins: ${Yj(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function Jj(e,t,n){if(EA(n))return{error:n.message??`Pi package management is not available on ${CA(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${CA(e)}: ${BA(Yj(t),e)}`}}}function Yj(e){return e instanceof Error?e.message:String(e)}function Xj(e,t){return{...e,config:Zj(e.config,t.config),effectiveConfig:Zj(e.effectiveConfig,t.effectiveConfig)}}function Zj(e,t){return{...e,...t.pathAccess===void 0?{}:{pathAccess:t.pathAccess},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes}}}function Qj(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function Y(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function $j(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?E(t,w.selectedMachineSettings)?{state:`supported`}:{state:`unsupported`,message:oM(e)}:{state:`unknown`}}function eM(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?E(t,w.agentProfileConfig)?{state:`supported`}:{state:`unsupported`,message:`Pi-compatible agent profile settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}:{state:`unknown`,message:`Pi-compatible agent profile support could not be verified on ${e.name}. Reload machine status before changing the profile.`}}function tM(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?E(t,w.modelTierSettings)?{state:`supported`}:{state:`unsupported`,message:oM(e)}:{state:`unknown`}}function nM(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?E(t,w.utilityModelSettings)?{state:`supported`}:{state:`unsupported`,message:oM(e)}:{state:`unknown`}}function rM(e){return`${e.state}:${e.message??``}`}function iM(e){return e?.state===`unsupported`}function aM(e){return e?.state===`supported`}function oM(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}function sM(e,t){let n=e.trim();return t.kind===`remote`?cM(n)?oM(t):n===`Remote machine timeout`?`Timed out while contacting ${t.name} for selected-machine settings. The operation may still be running remotely; reload before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for selected-machine settings. Check the machine connection and try again.`:n:n}function cM(e){return e===`Not Found`||/route\s+(GET|PUT):?\/api\/(config|plugins)\b.*not found/iu.test(e)||/cannot\s+(GET|PUT)\s+.*\/api\/(config|plugins)\b/iu.test(e)}function lM(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function uM(e,t){return{...e,config:dM(e.config,t.config),effectiveConfig:dM(e.effectiveConfig,t.effectiveConfig)}}function dM(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var X=class extends y{constructor(...e){super(...e),this.section=`general`,this.actions=[],this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.modelTiersLoading=!0,this.utilityModelsLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.modelTiersError=``,this.utilityModelsError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0,this.modelTiersLoadRequestSeq=0,this.utilityModelsLoadRequestSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget(),this.loadModelTiersForTarget(),this.loadUtilityModelsForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){let t=this.settingsTarget();if(e.has(`machine`)&&Qj(e.get(`machine`)).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t),this.resetModelTiersStateForTargetChange(),this.isConnected&&this.loadModelTiersForTarget(t),this.resetUtilityModelsStateForTargetChange(),this.isConnected&&this.loadUtilityModelsForTarget(t);return}e.has(`machineRuntime`)&&(this.selectedMachineSettingsSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetModelTiersStateForTargetChange(),this.isConnected&&this.loadModelTiersForTarget(t)),this.utilityModelSettingsSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetUtilityModelsStateForTargetChange(),this.isConnected&&this.loadUtilityModelsForTarget(t)),this.packageManagementSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return g`
|
|
5733
5735
|
<div class="backdrop" @mousedown=${()=>this.onClose?.()}>
|
|
5734
5736
|
<section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEBUI settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
5735
5737
|
<header class="settings-header">
|
|
@@ -5850,7 +5852,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5850
5852
|
<strong>${t}</strong>
|
|
5851
5853
|
<small>${n}</small>
|
|
5852
5854
|
</button>
|
|
5853
|
-
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await Kj({loadConfig:()=>Yo.config(),loadPlugins:()=>Xo.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(rM(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await Yo.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${Y(e)}: ${oM(dM(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(rM(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await Yo.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${Y(e)}: ${oM(dM(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(rM(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([Yo.config(e.id),Xo.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${oM(dM(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${oM(dM(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${Y(e)}: ${i.join(`; `)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await qj(e,e=>cs.packages(e),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async loadModelTiersForTarget(e=this.settingsTarget()){let t=++this.modelTiersLoadRequestSeq,n=this.modelTierSettingsSupport(e);if(rM(n)){this.modelTiersConfigResponse=void 0,this.modelTiersLoading=!1,this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.modelTiersLoading=!0,this.modelTiersError=``;try{let n=await es.settings(e.id);if(!this.isCurrentModelTiersLoad(t,e))return;this.modelTiersConfigResponse=n}catch(n){this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersError=`Failed to load model tier settings from ${Y(e)}: ${oM(dM(n),e)}`)}finally{this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersLoading=!1)}}async loadUtilityModelsForTarget(e=this.settingsTarget()){let t=++this.utilityModelsLoadRequestSeq,n=this.utilityModelSettingsSupport(e);if(rM(n)){this.utilityModelsConfigResponse=void 0,this.utilityModelsLoading=!1,this.utilityModelsError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.utilityModelsLoading=!0,this.utilityModelsError=``;try{let n=await rs.settings(e.id);if(!this.isCurrentUtilityModelsLoad(t,e))return;this.utilityModelsConfigResponse=n}catch(n){this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsError=`Failed to load utility model settings from ${Y(e)}: ${oM(dM(n),e)}`)}finally{this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(rM(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${Y(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${Y(n)}. Reload before changing plugin enablement.`;return}let i=cM(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await Yo.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=lM(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEBUI plugin config on ${Y(n)}: ${oM(dM(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await Yo.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${dM(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(rM(n)){this.accessError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await Yo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=Yj(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${Y(t)}: ${oM(dM(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(rM(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!iM(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${Y(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await Yo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=pA(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${Y(t)}: ${oM(dM(e),t)}`)}finally{this.saving=!1}}async saveModelTiers(e){if(this.saving)return;let t=this.settingsTarget(),n=this.modelTierSettingsSupport(t);if(rM(n)){this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.modelTiersError=``,this.savedMessage=``;try{let n=await es.save(e,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.modelTiersConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&n.ladder!==void 0){let e=n.ladder;this.configResponse={...this.configResponse,config:{...this.configResponse.config,modelTiers:e},effectiveConfig:{...this.configResponse.effectiveConfig,modelTiers:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.onModelTiersSaved?.(t.id,n),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.modelTiersError=`Failed to save model tier settings on ${Y(t)}: ${oM(dM(e),t)}`)}finally{this.saving=!1}}async saveUtilityModels(e){if(this.saving)return;let t=this.settingsTarget(),n=this.utilityModelsConfigResponse;if(n===void 0){this.utilityModelsError=`Utility model settings must be loaded before saving.`;return}let r=this.utilityModelSettingsSupport(t);if(rM(r)){this.utilityModelsError=r.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.utilityModelsError=``,this.savedMessage=``;try{let r=await rs.save(e,n.contractVersion,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.utilityModelsConfigResponse=r,t.kind===`local`&&this.configResponse!==void 0){let e=r.settings;this.configResponse={...this.configResponse,config:{...this.configResponse.config,utilityModels:e},effectiveConfig:{...this.configResponse.effectiveConfig,utilityModels:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.utilityModelsError=`Failed to save utility model settings on ${Y(t)}: ${oM(dM(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>cs.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>cs.remove(e,t,n.id))}async updatePiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:`update-all`}:{kind:`update`,source:e},`update Pi packages`,t,()=>cs.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(TA(i))throw this.packageError=i.message??`Pi package management is not available on ${SA(n)}.`,Error(this.packageError);if(this.saving)throw Error(`A settings operation is already running.`);let a=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(a,n))return;this.packagesResponse={packages:e.packages};let t=DA(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=RA(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${SA(n)}: ${zA(dM(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Xo.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${dM(e)}`}}async refreshPluginsForTarget(e){try{let t=await Xo.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${Y(e)}: ${oM(dM(t),e)}`}}settingsTarget(){return Zj(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return Qj(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return $j(e,this.machineRuntime)}modelTierSettingsSupport(e=this.settingsTarget()){return eM(e,this.machineRuntime)}utilityModelSettingsSupport(e=this.settingsTarget()){return tM(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=Qj(t,e),r=this.selectedMachineSettingsSupport(t);return nM(n)!==nM(r)}utilityModelSettingsSupportNeedsReload(e,t){let n=tM(t,e),r=this.utilityModelSettingsSupport(t);return nM(n)!==nM(r)}packageManagementSupport(e=this.packageTarget()){return CA(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=CA(t,e),r=this.packageManagementSupport(t);return wA(n)===wA(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentModelTiersLoad(e,t){return e===this.modelTiersLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentUtilityModelsLoad(e,t){return e===this.utilityModelsLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}resetModelTiersStateForTargetChange(){this.modelTiersLoadRequestSeq+=1,this.modelTiersLoading=!1,this.modelTiersError=``,this.modelTiersConfigResponse=void 0,this.savedMessage=``}resetUtilityModelsStateForTargetChange(){this.utilityModelsLoadRequestSeq+=1,this.utilityModelsLoading=!1,this.utilityModelsError=``,this.utilityModelsConfigResponse=void 0,this.savedMessage=``}showSavedMessage(){this.savedMessage=`Config saved.`,this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage===`Config saved.`&&(this.savedMessage=``),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}static{this.styles=h`
|
|
5855
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await qj({loadConfig:()=>Yo.config(),loadPlugins:()=>Xo.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(iM(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await Yo.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${Y(e)}: ${sM(fM(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(iM(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await Yo.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${Y(e)}: ${sM(fM(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(iM(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([Yo.config(e.id),Xo.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${sM(fM(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${sM(fM(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${Y(e)}: ${i.join(`; `)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await Jj(e,e=>cs.packages(e),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async loadModelTiersForTarget(e=this.settingsTarget()){let t=++this.modelTiersLoadRequestSeq,n=this.modelTierSettingsSupport(e);if(iM(n)){this.modelTiersConfigResponse=void 0,this.modelTiersLoading=!1,this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.modelTiersLoading=!0,this.modelTiersError=``;try{let n=await es.settings(e.id);if(!this.isCurrentModelTiersLoad(t,e))return;this.modelTiersConfigResponse=n}catch(n){this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersError=`Failed to load model tier settings from ${Y(e)}: ${sM(fM(n),e)}`)}finally{this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersLoading=!1)}}async loadUtilityModelsForTarget(e=this.settingsTarget()){let t=++this.utilityModelsLoadRequestSeq,n=this.utilityModelSettingsSupport(e);if(iM(n)){this.utilityModelsConfigResponse=void 0,this.utilityModelsLoading=!1,this.utilityModelsError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.utilityModelsLoading=!0,this.utilityModelsError=``;try{let n=await rs.settings(e.id);if(!this.isCurrentUtilityModelsLoad(t,e))return;this.utilityModelsConfigResponse=n}catch(n){this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsError=`Failed to load utility model settings from ${Y(e)}: ${sM(fM(n),e)}`)}finally{this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(iM(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${Y(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${Y(n)}. Reload before changing plugin enablement.`;return}let i=lM(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await Yo.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=uM(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEBUI plugin config on ${Y(n)}: ${sM(fM(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await Yo.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${fM(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(iM(n)){this.accessError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await Yo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=Xj(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${Y(t)}: ${sM(fM(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(iM(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!aM(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${Y(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await Yo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=mA(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${Y(t)}: ${sM(fM(e),t)}`)}finally{this.saving=!1}}async saveModelTiers(e){if(this.saving)return;let t=this.settingsTarget(),n=this.modelTierSettingsSupport(t);if(iM(n)){this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.modelTiersError=``,this.savedMessage=``;try{let n=await es.save(e,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.modelTiersConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&n.ladder!==void 0){let e=n.ladder;this.configResponse={...this.configResponse,config:{...this.configResponse.config,modelTiers:e},effectiveConfig:{...this.configResponse.effectiveConfig,modelTiers:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.onModelTiersSaved?.(t.id,n),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.modelTiersError=`Failed to save model tier settings on ${Y(t)}: ${sM(fM(e),t)}`)}finally{this.saving=!1}}async saveUtilityModels(e){if(this.saving)return;let t=this.settingsTarget(),n=this.utilityModelsConfigResponse;if(n===void 0){this.utilityModelsError=`Utility model settings must be loaded before saving.`;return}let r=this.utilityModelSettingsSupport(t);if(iM(r)){this.utilityModelsError=r.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.utilityModelsError=``,this.savedMessage=``;try{let r=await rs.save(e,n.contractVersion,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.utilityModelsConfigResponse=r,t.kind===`local`&&this.configResponse!==void 0){let e=r.settings;this.configResponse={...this.configResponse,config:{...this.configResponse.config,utilityModels:e},effectiveConfig:{...this.configResponse.effectiveConfig,utilityModels:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.utilityModelsError=`Failed to save utility model settings on ${Y(t)}: ${sM(fM(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>cs.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>cs.remove(e,t,n.id))}async updatePiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:`update-all`}:{kind:`update`,source:e},`update Pi packages`,t,()=>cs.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(EA(i))throw this.packageError=i.message??`Pi package management is not available on ${CA(n)}.`,Error(this.packageError);if(this.saving)throw Error(`A settings operation is already running.`);let a=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(a,n))return;this.packagesResponse={packages:e.packages};let t=OA(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=zA(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${CA(n)}: ${BA(fM(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Xo.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${fM(e)}`}}async refreshPluginsForTarget(e){try{let t=await Xo.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${Y(e)}: ${sM(fM(t),e)}`}}settingsTarget(){return Qj(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return $j(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return eM(e,this.machineRuntime)}modelTierSettingsSupport(e=this.settingsTarget()){return tM(e,this.machineRuntime)}utilityModelSettingsSupport(e=this.settingsTarget()){return nM(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=$j(t,e),r=this.selectedMachineSettingsSupport(t);return rM(n)!==rM(r)}utilityModelSettingsSupportNeedsReload(e,t){let n=nM(t,e),r=this.utilityModelSettingsSupport(t);return rM(n)!==rM(r)}packageManagementSupport(e=this.packageTarget()){return wA(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=wA(t,e),r=this.packageManagementSupport(t);return TA(n)===TA(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentModelTiersLoad(e,t){return e===this.modelTiersLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentUtilityModelsLoad(e,t){return e===this.utilityModelsLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}resetModelTiersStateForTargetChange(){this.modelTiersLoadRequestSeq+=1,this.modelTiersLoading=!1,this.modelTiersError=``,this.modelTiersConfigResponse=void 0,this.savedMessage=``}resetUtilityModelsStateForTargetChange(){this.utilityModelsLoadRequestSeq+=1,this.utilityModelsLoading=!1,this.utilityModelsError=``,this.utilityModelsConfigResponse=void 0,this.savedMessage=``}showSavedMessage(){this.savedMessage=`Config saved.`,this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage===`Config saved.`&&(this.savedMessage=``),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}static{this.styles=h`
|
|
5854
5856
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
5855
5857
|
.backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
|
|
5856
5858
|
.settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -5877,7 +5879,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5877
5879
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
5878
5880
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
5879
5881
|
}
|
|
5880
|
-
`}};B([x({attribute:!1})],X.prototype,`section`,void 0),B([x({attribute:!1})],X.prototype,`actions`,void 0),B([x({attribute:!1})],X.prototype,`machine`,void 0),B([x({attribute:!1})],X.prototype,`machineRuntime`,void 0),B([x({attribute:!1})],X.prototype,`onNavigate`,void 0),B([x({attribute:!1})],X.prototype,`onClose`,void 0),B([x({attribute:!1})],X.prototype,`onConfigSaved`,void 0),B([x({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),B([x({attribute:!1})],X.prototype,`onModelTiersSaved`,void 0),B([S()],X.prototype,`configResponse`,void 0),B([S()],X.prototype,`accessConfigResponse`,void 0),B([S()],X.prototype,`sessiondConfigResponse`,void 0),B([S()],X.prototype,`pluginsResponse`,void 0),B([S()],X.prototype,`selectedPluginConfigResponse`,void 0),B([S()],X.prototype,`selectedPluginsResponse`,void 0),B([S()],X.prototype,`packagesResponse`,void 0),B([S()],X.prototype,`modelTiersConfigResponse`,void 0),B([S()],X.prototype,`utilityModelsConfigResponse`,void 0),B([S()],X.prototype,`loading`,void 0),B([S()],X.prototype,`accessLoading`,void 0),B([S()],X.prototype,`sessiondLoading`,void 0),B([S()],X.prototype,`pluginLoading`,void 0),B([S()],X.prototype,`packageLoading`,void 0),B([S()],X.prototype,`modelTiersLoading`,void 0),B([S()],X.prototype,`utilityModelsLoading`,void 0),B([S()],X.prototype,`saving`,void 0),B([S()],X.prototype,`packageOperation`,void 0),B([S()],X.prototype,`error`,void 0),B([S()],X.prototype,`accessError`,void 0),B([S()],X.prototype,`sessiondError`,void 0),B([S()],X.prototype,`pluginError`,void 0),B([S()],X.prototype,`packageError`,void 0),B([S()],X.prototype,`modelTiersError`,void 0),B([S()],X.prototype,`utilityModelsError`,void 0),B([S()],X.prototype,`savedMessage`,void 0),B([S()],X.prototype,`packageMessage`,void 0),X=B([b(`settings-dialog`)],X);function
|
|
5882
|
+
`}};B([x({attribute:!1})],X.prototype,`section`,void 0),B([x({attribute:!1})],X.prototype,`actions`,void 0),B([x({attribute:!1})],X.prototype,`machine`,void 0),B([x({attribute:!1})],X.prototype,`machineRuntime`,void 0),B([x({attribute:!1})],X.prototype,`onNavigate`,void 0),B([x({attribute:!1})],X.prototype,`onClose`,void 0),B([x({attribute:!1})],X.prototype,`onConfigSaved`,void 0),B([x({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),B([x({attribute:!1})],X.prototype,`onModelTiersSaved`,void 0),B([S()],X.prototype,`configResponse`,void 0),B([S()],X.prototype,`accessConfigResponse`,void 0),B([S()],X.prototype,`sessiondConfigResponse`,void 0),B([S()],X.prototype,`pluginsResponse`,void 0),B([S()],X.prototype,`selectedPluginConfigResponse`,void 0),B([S()],X.prototype,`selectedPluginsResponse`,void 0),B([S()],X.prototype,`packagesResponse`,void 0),B([S()],X.prototype,`modelTiersConfigResponse`,void 0),B([S()],X.prototype,`utilityModelsConfigResponse`,void 0),B([S()],X.prototype,`loading`,void 0),B([S()],X.prototype,`accessLoading`,void 0),B([S()],X.prototype,`sessiondLoading`,void 0),B([S()],X.prototype,`pluginLoading`,void 0),B([S()],X.prototype,`packageLoading`,void 0),B([S()],X.prototype,`modelTiersLoading`,void 0),B([S()],X.prototype,`utilityModelsLoading`,void 0),B([S()],X.prototype,`saving`,void 0),B([S()],X.prototype,`packageOperation`,void 0),B([S()],X.prototype,`error`,void 0),B([S()],X.prototype,`accessError`,void 0),B([S()],X.prototype,`sessiondError`,void 0),B([S()],X.prototype,`pluginError`,void 0),B([S()],X.prototype,`packageError`,void 0),B([S()],X.prototype,`modelTiersError`,void 0),B([S()],X.prototype,`utilityModelsError`,void 0),B([S()],X.prototype,`savedMessage`,void 0),B([S()],X.prototype,`packageMessage`,void 0),X=B([b(`settings-dialog`)],X);function fM(e){return e instanceof Error?e.message:String(e)}var pM=class extends y{constructor(...e){super(...e),this.sessionsApi=hs,this.loading=!0,this.error=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSystemPrompt()}updated(e){let t=e.has(`session`)&&hM(e.get(`session`))!==hM(this.session),n=e.has(`machine`)&&mM(e.get(`machine`))!==mM(this.machine);(t||n)&&this.isConnected&&this.loadSystemPrompt()}render(){return g`
|
|
5881
5883
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
5882
5884
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="system-prompt-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
5883
5885
|
<header>
|
|
@@ -5886,7 +5888,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5886
5888
|
<h1 id="system-prompt-dialog-title">System prompt</h1>
|
|
5887
5889
|
</div>
|
|
5888
5890
|
<button class="icon-button" type="button" title="Close system prompt" aria-label="Close system prompt" @click=${()=>{this.close()}}>
|
|
5889
|
-
${
|
|
5891
|
+
${yM()}
|
|
5890
5892
|
</button>
|
|
5891
5893
|
</header>
|
|
5892
5894
|
<div class="prompt-body" aria-live="polite">
|
|
@@ -5897,7 +5899,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5897
5899
|
</footer>
|
|
5898
5900
|
</section>
|
|
5899
5901
|
</div>
|
|
5900
|
-
`}renderPrompt(){return this.loading?g`<p class="prompt-state">Loading system prompt…</p>`:this.error===``?this.systemPrompt===void 0?g`<p class="prompt-state">Send a message to load the system prompt</p>`:this.systemPrompt===``?g`<p class="prompt-state">System prompt is empty (tools are disabled)</p>`:g`<pre class="system-prompt">${this.systemPrompt}</pre>`:g`<p class="prompt-state error">${this.error}</p>`}async loadSystemPrompt(){let e=this.session,t=e===void 0?void 0:
|
|
5902
|
+
`}renderPrompt(){return this.loading?g`<p class="prompt-state">Loading system prompt…</p>`:this.error===``?this.systemPrompt===void 0?g`<p class="prompt-state">Send a message to load the system prompt</p>`:this.systemPrompt===``?g`<p class="prompt-state">System prompt is empty (tools are disabled)</p>`:g`<pre class="system-prompt">${this.systemPrompt}</pre>`:g`<p class="prompt-state error">${this.error}</p>`}async loadSystemPrompt(){let e=this.session,t=e===void 0?void 0:_M(mM(this.machine),e),n=++this.loadRequestSequence;if(this.loading=!0,this.error=``,this.systemPrompt=void 0,e===void 0||t===void 0){this.loading=!1;return}try{let r=await this.sessionsApi.systemPrompt(e,mM(this.machine));if(!this.isCurrentLoad(n,t))return;this.systemPrompt=r.systemPrompt}catch(e){if(!this.isCurrentLoad(n,t))return;this.error=`Failed to load system prompt: ${vM(e)}`}finally{this.isCurrentLoad(n,t)&&(this.loading=!1)}}isCurrentLoad(e,t){let n=this.session;return e===this.loadRequestSequence&&n!==void 0&&_M(mM(this.machine),n)===t}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}static{this.styles=h`
|
|
5901
5903
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
5902
5904
|
* { box-sizing: border-box; }
|
|
5903
5905
|
.backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
|
|
@@ -5923,11 +5925,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5923
5925
|
header, footer { padding: 12px; }
|
|
5924
5926
|
.system-prompt, .prompt-state { padding: 12px; }
|
|
5925
5927
|
}
|
|
5926
|
-
`}};B([x({attribute:!1})],
|
|
5928
|
+
`}};B([x({attribute:!1})],pM.prototype,`machine`,void 0),B([x({attribute:!1})],pM.prototype,`session`,void 0),B([x({attribute:!1})],pM.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],pM.prototype,`onClose`,void 0),B([S()],pM.prototype,`systemPrompt`,void 0),B([S()],pM.prototype,`loading`,void 0),B([S()],pM.prototype,`error`,void 0),pM=B([b(`system-prompt-dialog`)],pM);function mM(e){return e?.id??`local`}function hM(e){return e===void 0?void 0:gM(e)}function gM(e){return JSON.stringify([e.id,e.cwd])}function _M(e,t){return JSON.stringify([e,t.id,t.cwd])}function vM(e){return e instanceof Error?e.message:String(e)}function yM(){return _`
|
|
5927
5929
|
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
5928
5930
|
<path d="M6 6l12 12M18 6 6 18"></path>
|
|
5929
5931
|
</svg>
|
|
5930
|
-
`}var
|
|
5932
|
+
`}var bM=class extends y{constructor(...e){super(...e),this.tool=`core:workspace.files`,this.panels=[],this.hiddenTools=[],this.hideToolTabs=!1,this.onSelectTool=()=>void 0,this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:`Select a workspace`,body:`Choose a workspace to inspect files, Git, or terminals.`});let e=this.panelContext;if(e===void 0)return this.renderEmptyState({title:`Workspace tools unavailable`,body:`Try selecting the workspace again.`});let t=this.panels,n=t.filter(e=>!this.hiddenTools.includes(e.id)),r=t.find(e=>e.id===this.tool)??t[0];return g`
|
|
5931
5933
|
${this.hideToolTabs?null:g`
|
|
5932
5934
|
<header>
|
|
5933
5935
|
<div class=${this.workspaceHeaderFrameClass()}>
|
|
@@ -5957,10 +5959,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5957
5959
|
<h2>${e.title}</h2>
|
|
5958
5960
|
${e.body===void 0?null:g`<p>${e.body}</p>`}
|
|
5959
5961
|
</section>
|
|
5960
|
-
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>`u`)&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=Qg}};B([x({attribute:!1})],
|
|
5961
|
-
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function
|
|
5962
|
+
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>`u`)&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=Qg}};B([x({attribute:!1})],bM.prototype,`workspace`,void 0),B([x({attribute:!1})],bM.prototype,`panelContext`,void 0),B([x({attribute:!1})],bM.prototype,`emptyState`,void 0),B([x()],bM.prototype,`tool`,void 0),B([x({attribute:!1})],bM.prototype,`panels`,void 0),B([x({attribute:!1})],bM.prototype,`hiddenTools`,void 0),B([x({type:Boolean})],bM.prototype,`hideToolTabs`,void 0),B([x({attribute:!1})],bM.prototype,`onSelectTool`,void 0),B([C(`.workspace-header-strip`)],bM.prototype,`workspaceHeaderStrip`,void 0),B([S()],bM.prototype,`workspaceHeaderCanScrollLeft`,void 0),B([S()],bM.prototype,`workspaceHeaderCanScrollRight`,void 0),bM=B([b(`workspace-panel`)],bM);var xM=`important`,SM=` !important`,CM=Hb(class extends Ub{constructor(e){if(super(e),e.type!==Vb.ATTRIBUTE||e.name!==`style`||e.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(e){return Object.keys(e).reduce((t,n)=>{let r=e[n];return r==null?t:t+`${n=n.includes(`-`)?n:n.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,`-$&`).toLowerCase()}:${r};`},``)}update(e,[t]){let{style:n}=e.element;if(this.ft===void 0)return this.ft=new Set(Object.keys(t)),this.render(t);for(let e of this.ft)t[e]??(this.ft.delete(e),e.includes(`-`)?n.removeProperty(e):n[e]=null);for(let e in t){let r=t[e];if(r!=null){this.ft.add(e);let t=typeof r==`string`&&r.endsWith(SM);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?xM:``):n[e]=r}}return Qe}}),wM=`#ffffff`,TM=`#000000`,EM=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],DM=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],OM={black:EM[0],red:EM[1],green:EM[2],yellow:EM[3],blue:EM[4],magenta:EM[5],cyan:EM[6],white:EM[7],brightBlack:EM[8],brightRed:EM[9],brightGreen:EM[10],brightYellow:EM[11],brightBlue:EM[12],brightMagenta:EM[13],brightCyan:EM[14],brightWhite:EM[15]};function kM(e,t,n={}){let r=Math.max(0,Math.floor(t));if(e.length<=0||r===0)return{text:``,lines:[],physicalLineCount:0,viewportLine:0};let i=LM(n.theme),a=n.theme?.foreground??wM,o=n.theme?.background??TM,s=[],c=e.getNullCell(),l=-1;for(let t=0;t<e.length;t+=1){let u=e.getLine(t);if(u===void 0){s.push({text:``,runs:[],wrapped:!1});continue}let d=AM(u,r,c,{palette:i,foreground:a,background:o,drawBoldTextInBrightColors:n.drawBoldTextInBrightColors!==!1});s.push(d),(d.text!==``||d.runs.some(e=>e.style.background!==o))&&(l=t)}let u=Math.min(e.length-1,Math.max(0,e.baseY+e.cursorY)),d=Math.max(l,u),f=s.slice(0,d+1),p=[];for(let e of f){let t=p.at(-1);if(e.wrapped&&t!==void 0){t.text+=e.text,PM(t.runs,e.runs);continue}p.push({text:e.text,runs:e.runs.map(e=>({text:e.text,style:e.style}))})}return{text:p.map(e=>e.text).join(`
|
|
5963
|
+
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function AM(e,t,n,r){let i=[],a=Math.min(t,e.length);for(let t=0;t<a;t+=1){let a=e.getCell(t,n);if(a===void 0){i.push({text:` `,meaningful:!1,style:NM(r)});continue}let o=a.getWidth();if(o===0)continue;let s=a.getChars();i.push({text:s===``?` `.repeat(Math.max(1,o)):s,meaningful:s!==``||!a.isAttributeDefault(),style:jM(a,r)})}let o=i.length-1;for(;o>=0&&i[o]?.meaningful!==!0;)--o;let s=[],c=``;for(let e=0;e<=o;e+=1){let t=i[e];t!==void 0&&(c+=t.text,FM(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function jM(e,t){let n=e.isInverse()!==0,r=MM(e,`foreground`,t),i=MM(e,`background`,t);if(n&&([r,i]=[i,r]),e.isBold()!==0&&t.drawBoldTextInBrightColors){let i=n?e.isBgPalette()?e.getBgColor():void 0:e.isFgPalette()?e.getFgColor():void 0;i!==void 0&&i>=0&&i<8&&(r=t.palette[i+8]??r)}return{foreground:r,background:i,bold:e.isBold()!==0,italic:e.isItalic()!==0,dim:e.isDim()!==0,underline:e.isUnderline()!==0,invisible:e.isInvisible()!==0,strikethrough:e.isStrikethrough()!==0,overline:e.isOverline()!==0}}function MM(e,t,n){let r=t===`foreground`?e.isFgRGB():e.isBgRGB(),i=t===`foreground`?e.isFgPalette():e.isBgPalette(),a=t===`foreground`?e.getFgColor():e.getBgColor();return r?RM(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function NM(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function PM(e,t){for(let n of t)FM(e,n)}function FM(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&IM(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function IM(e,t){return e.foreground===t.foreground&&e.background===t.background&&e.bold===t.bold&&e.italic===t.italic&&e.dim===t.dim&&e.underline===t.underline&&e.invisible===t.invisible&&e.strikethrough===t.strikethrough&&e.overline===t.overline}function LM(e){let t=[...EM];for(let n=0;n<DM.length;n+=1){let r=DM[n];if(r===void 0)continue;let i=e?.[r];typeof i==`string`&&(t[n]=i)}let n=[0,95,135,175,215,255];for(let e=0;e<216;e+=1){let r=n[Math.floor(e/36)%6]??0,i=n[Math.floor(e/6)%6]??0,a=n[e%6]??0;t.push(zM(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(zM(n,n,n))}for(let n=0;n<Math.min(e?.extendedAnsi?.length??0,240);n+=1){let r=e?.extendedAnsi?.[n];r!==void 0&&(t[n+16]=r)}return t}function RM(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function zM(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var BM=`pi-webui.terminal.softKeys`,VM=`(pointer: coarse), (max-width: 760px)`;function HM(e,t){return e??t}function UM(e){if(e===`true`)return!0;if(e===`false`)return!1}function WM(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(VM):void 0}function GM(e){return e?.matches===!0}function KM(e=WM()){return HM(JM(),GM(e))}function qM(){return JM()!==void 0}function JM(e=XM()){if(e!==void 0)try{return UM(e.getItem(BM))}catch{return}}function YM(e,t=XM()){if(t!==void 0)try{t.setItem(BM,String(e))}catch{}}function XM(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var ZM=[{id:`escape`,label:`Esc`,ariaLabel:`Escape`,title:`Send Escape`},{id:`tab`,label:`Tab`,ariaLabel:`Tab`,title:`Send Tab`},{id:`ctrl-c`,label:`Ctrl+C`,ariaLabel:`Control C`,title:`Interrupt the foreground process`},{id:`ctrl-d`,label:`Ctrl+D`,ariaLabel:`Control D`,title:`Send EOF / close input`},{id:`ctrl-z`,label:`Ctrl+Z`,ariaLabel:`Control Z`,title:`Suspend the foreground process`},{id:`ctrl-l`,label:`Ctrl+L`,ariaLabel:`Control L`,title:`Clear / redraw the terminal`},{id:`ctrl-r`,label:`Ctrl+R`,ariaLabel:`Control R`,title:`Reverse search history`},{id:`ctrl-u`,label:`Ctrl+U`,ariaLabel:`Control U`,title:`Delete to the start of the line`},{id:`ctrl-w`,label:`Ctrl+W`,ariaLabel:`Control W`,title:`Delete the previous word`},{id:`arrow-left`,label:`←`,ariaLabel:`Left arrow`,title:`Move left`},{id:`arrow-up`,label:`↑`,ariaLabel:`Up arrow`,title:`Move up / previous command`},{id:`arrow-down`,label:`↓`,ariaLabel:`Down arrow`,title:`Move down / next command`},{id:`arrow-right`,label:`→`,ariaLabel:`Right arrow`,title:`Move right`},{id:`home`,label:`Home`,ariaLabel:`Home`,title:`Move to the start`},{id:`end`,label:`End`,ariaLabel:`End`,title:`Move to the end`},{id:`page-up`,label:`PgUp`,ariaLabel:`Page up`,title:`Page up`},{id:`page-down`,label:`PgDn`,ariaLabel:`Page down`,title:`Page down`},{id:`delete`,label:`Del`,ariaLabel:`Delete`,title:`Delete forward`},{id:`backspace`,label:`⌫`,ariaLabel:`Backspace`,title:`Backspace`},{id:`meta-backward-word`,label:`M-B`,ariaLabel:`Meta B`,title:`Move backward one word`},{id:`meta-forward-word`,label:`M-F`,ariaLabel:`Meta F`,title:`Move forward one word`}],QM=`\x1B`,$M=``;function eN(e,t){switch(e){case`escape`:return QM;case`tab`:return` `;case`ctrl-c`:return tN(`c`);case`ctrl-d`:return tN(`d`);case`ctrl-z`:return tN(`z`);case`ctrl-l`:return tN(`l`);case`ctrl-r`:return tN(`r`);case`ctrl-u`:return tN(`u`);case`ctrl-w`:return tN(`w`);case`arrow-left`:return nN(`D`,t);case`arrow-up`:return nN(`A`,t);case`arrow-down`:return nN(`B`,t);case`arrow-right`:return nN(`C`,t);case`home`:return rN(`H`,t);case`end`:return rN(`F`,t);case`page-up`:return`${QM}[5~`;case`page-down`:return`${QM}[6~`;case`delete`:return`${QM}[3~`;case`backspace`:return $M;case`meta-backward-word`:return`${QM}b`;case`meta-forward-word`:return`${QM}f`}}function tN(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function nN(e,t){return t?.applicationCursorKeysMode===!0?`${QM}O${e}`:`${QM}[${e}`}function rN(e,t){return t?.applicationCursorKeysMode===!0?`${QM}O${e}`:`${QM}[${e}`}var iN=8,aN=500,oN=class extends y{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(eN(e.id,this.modes),t)}onSoftKeyPointerDown(e,t){e.pointerType===`mouse`&&e.button!==0||(e.preventDefault(),this.pointerStart={pointerId:e.pointerId,key:t,clientX:e.clientX,clientY:e.clientY})}onSoftKeyPointerMove(e){let t=this.pointerStart;t?.pointerId===e.pointerId&&sN(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||sN(n,e))&&this.sendSoftKey(t,{refocus:e.pointerType===`mouse`}))}onSoftKeyPointerCancel(e){this.pointerStart?.pointerId===e.pointerId&&this.finishSoftKeyPointer()}finishSoftKeyPointer(){this.pointerStart=void 0,this.lastPointerFinishedAt=Date.now()}onSoftKeyClick(e,t){if(Date.now()-this.lastPointerFinishedAt<aN){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return g`
|
|
5962
5964
|
<div class="terminal-soft-keys" role="toolbar" aria-label="Terminal soft keys">
|
|
5963
|
-
${
|
|
5965
|
+
${ZM.map(e=>g`
|
|
5964
5966
|
<button
|
|
5965
5967
|
type="button"
|
|
5966
5968
|
class="soft-key"
|
|
@@ -5980,7 +5982,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5980
5982
|
.terminal-soft-keys::-webkit-scrollbar { display: none; }
|
|
5981
5983
|
button { display: inline-flex; align-items: center; gap: 6px; flex: 0 0 auto; max-width: none; min-height: 34px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 6px 9px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; cursor: pointer; touch-action: pan-x; -webkit-touch-callout: none; user-select: none; }
|
|
5982
5984
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
5983
|
-
`}};B([x({attribute:!1})],aN.prototype,`modes`,void 0),B([x({type:Boolean})],aN.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],aN.prototype,`onInput`,void 0),aN=B([b(`terminal-soft-keys`)],aN);function oN(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>rN}var sN=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>SN,terminalBackgroundWithOpacity:()=>ON}),cN={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},lN={cols:100,rows:30},uN=1e3,dN=500,fN=5e3,pN=1.6,mN=`--pi-terminal-effective-bg`,hN=`--pi-terminal-ui-opacity`,Z=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.autoStart=!1,this.fontSize=13,this.bgOpacity=100,this.onSelectTerminal=()=>void 0,this.terminals=[],this.commandRuns=[],this.loading=!1,this.visible=!1,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.defaultSoftKeysEnvironment=!1,this.softKeysEnabled=GM(),this.suppressTerminalInput=!1,this.terminalReconnectDelay=dN,this.softKeysDefaultEnvironmentMedia=UM(),this.softKeysPreferenceStored=KM(),this.onSoftKeysDefaultEnvironmentChange=()=>{this.syncDefaultSoftKeysEnvironment()}}connectedCallback(){super.connectedCallback(),this.syncTerminalBackground(),this.syncDefaultSoftKeysEnvironment(),this.softKeysDefaultEnvironmentMedia?.addEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.themeObserver=new MutationObserver(()=>{this.applyTerminalTheme()}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`,`style`,`data-theme`]})}firstUpdated(){this.intersectionObserver=new IntersectionObserver(e=>{this.visible=e[0]?.isIntersecting===!0}),this.intersectionObserver.observe(this)}disconnectedCallback(){this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.themeObserver?.disconnect(),this.themeObserver=void 0,this.softKeysDefaultEnvironmentMedia?.removeEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.updateCommandRunPolling(!1),this.disposeTerminalView(),super.disconnectedCallback()}syncDefaultSoftKeysEnvironment(){let e=WM(this.softKeysDefaultEnvironmentMedia),t=this.softKeysEnabled;this.defaultSoftKeysEnvironment=e,this.softKeysPreferenceStored||(this.softKeysEnabled=e),this.softKeysEnabled!==t&&this.scheduleFitAndNotify()}scheduleFitAndNotify(){this.updateComplete.then(()=>{this.fitAndNotify()})}willUpdate(e){e.has(`bgOpacity`)&&this.syncTerminalBackground();let t=this.workspace===void 0?void 0:JSON.stringify([this.machineId,this.workspace.path]);if(t!==this.observedWorkspaceScope){this.observedWorkspaceScope=t,this.loadedCwd=void 0,this.autoStartConsumedCwd=void 0,this.terminals=[],this.commandRuns=[],this.selectedId=void 0,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.updateCommandRunPolling(!1),this.disposeTerminalView();return}if(e.has(`selectedTerminalId`)){if(e.get(`selectedTerminalId`)!==void 0&&this.selectedTerminalId===void 0){this.loadedCwd=void 0,this.selectTerminalIdInView(void 0);return}this.applyRequestedTerminalSelection()}}updated(e){this.visible?this.hasPendingCommandRuns()&&this.updateCommandRunPolling(!0):this.updateCommandRunPolling(!1),this.loadVisibleWorkspaceTerminals(),e.has(`selectedTerminalId`)&&this.shouldReloadForRequestedTerminal()&&this.loadTerminals(),e.has(`fontSize`)&&this.terminal!==void 0&&(this.terminal.options.fontSize=this.fontSize,this.fitAndNotify()),e.has(`bgOpacity`)&&this.applyTerminalTheme(),this.ensureTerminalView()}loadVisibleWorkspaceTerminals(){let e=this.workspace?.path;!this.visible||e===void 0||e===this.loadedCwd||(this.loadedCwd=e,this.loadTerminals())}async loadTerminals(){this.loading=!0,this.error=void 0;try{let e=this.workspace;if(e===void 0)return;let t=this.consumeAutoStart(),[n,r]=await Promise.all([gs.terminals(e.projectId,e.id,this.machineId),gs.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId)]);this.terminals=n,this.commandRuns=r,this.selectPreferredLoadedTerminal({replaceUrl:!0}),this.updateCommandRunPolling(this.hasPendingCommandRuns(r)),n.length===0&&t&&await this.startTerminal()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}}applyRequestedTerminalSelection(){this.selectedTerminalId!==void 0&&!this.terminals.some(e=>e.id===this.selectedTerminalId)||this.selectPreferredLoadedTerminal({replaceUrl:!0})}consumeAutoStart(){let e=this.workspace?.path;return!this.autoStart||e===void 0||this.autoStartConsumedCwd===e?!1:(this.autoStartConsumedCwd=e,!0)}shouldReloadForRequestedTerminal(){let e=this.workspace?.path;return this.visible&&e!==void 0&&e===this.loadedCwd&&this.selectedTerminalId!==void 0&&!this.loading&&!this.terminals.some(e=>e.id===this.selectedTerminalId)}selectPreferredLoadedTerminal(e){let t=Jm(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=Ym(this.terminals)),this.selectTerminalIdInView(t?.id),(t?.id!==this.selectedTerminalId||t===void 0&&this.selectedTerminalId!==void 0)&&this.onSelectTerminal(t?.id,{replace:e?.replaceUrl===!0})}selectTerminalIdInView(e){this.selectedId!==e&&(this.selectedId=e,this.disposeTerminalView())}async startTerminal(){if(this.workspace!==void 0){this.error=void 0;try{let e=this.measureTerminalSize()??lN,t=await gs.startTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=[...this.terminals,t],this.selectTerminal(t.id)}catch(e){this.error=e instanceof Error?e.message:String(e)}}}async closeTerminal(e,t){t.stopPropagation();try{if(this.workspace===void 0)return;await gs.closeTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);let t=this.terminals.filter(t=>t.id!==e);if(this.terminals=t,this.selectedId===e||this.selectedTerminalId===e){let e=Ym(t)?.id;this.selectTerminalIdInView(e),this.onSelectTerminal(e,{replace:!0})}}catch(e){this.error=e instanceof Error?e.message:String(e)}}selectTerminal(e){this.selectedId!==e&&this.selectTerminalIdInView(e),this.onSelectTerminal(e)}selectedTerminalInfo(){return this.terminals.find(e=>e.id===this.selectedId)}selectedCommandRun(){let e=this.selectedTerminalInfo()?.commandRunId;if(e!==void 0)return this.commandRuns.find(t=>t.id===e)}async loadCommandRuns(){let e=this.workspace;if(e!==void 0)try{let t=await gs.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&yN(t))),this.updateCommandRunPolling(this.hasPendingCommandRuns(t))}catch(e){this.error=e instanceof Error?e.message:String(e)}}updateCommandRunPolling(e){if(e&&this.commandRunPollTimer===void 0){this.commandRunPollTimer=window.setInterval(()=>{this.loadCommandRuns()},uN);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(yN)}async cancelCommandRun(e){if(!(!yN(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await gs.cancelCommandRun(e.id,this.machineId),await this.loadCommandRuns()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.cancellingRunIds=this.cancellingRunIds.filter(t=>t!==e.id)}}}async continueTerminal(e){if(!(this.workspace===void 0||this.continuingTerminalIds.includes(e))){this.error=void 0,this.continuingTerminalIds=[...this.continuingTerminalIds,e];try{let t=await gs.continueTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=this.terminals.map(n=>n.id===e?t:n),this.socket===void 0&&this.disposeTerminalView(),this.fitAndNotify(),this.terminal?.focus()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.continuingTerminalIds=this.continuingTerminalIds.filter(t=>t!==e)}}}ensureTerminalView(){let e=this.workspace,t=this.terminalHostElement();if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||t===void 0||e===void 0)return;let n=new re(wN(this)),r=new ie;n.loadAddon(r),n.open(t),this.terminal=n,this.fitAddon=r,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(t),n.onData(e=>{this.suppressTerminalInput||this.copySnapshot!==void 0||this.sendTerminalInput(e)});let i=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,n,i),requestAnimationFrame(()=>{this.fitAndNotify()}),n.focus()}connectSocket(e,t,n,r,i){let a=Ts(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.socket===a&&(this.terminalReconnectDelay=dN,this.fitAndNotify())}),a.addEventListener(`message`,e=>{this.handleSocketMessage(e.data,n,r)}),a.addEventListener(`close`,()=>{if(this.socket!==a||(this.socket=void 0,this.terminals.some(e=>e.id===n&&e.exited)))return;this.terminalReconnectTimer!==void 0&&window.clearTimeout(this.terminalReconnectTimer);let o=this.terminalReconnectDelay;this.terminalReconnectDelay=Math.min(this.terminalReconnectDelay*pN,fN),this.terminalReconnectTimer=window.setTimeout(()=>{this.terminalReconnectTimer=void 0,!(this.socket!==void 0||this.terminals.some(e=>e.id===n&&e.exited))&&this.connectSocket(e,t,n,r,i)},o)})}async handleSocketMessage(e,t,n){try{let r=xN(await CN(e));r.type===`output`&&this.writeTerminalOutput(n,r.data,r.replay===!0),r.type===`exit`&&(n.writeln(`\r\n[process exited${r.exitCode===void 0?``:` with code ${String(r.exitCode)}`}]`),this.terminals=this.terminals.map(e=>e.id===t?{...e,exited:!0,...r.exitCode===void 0?{}:{exitCode:r.exitCode}}:e),this.loadCommandRuns()),r.type===`error`&&n.writeln(`\r\n[terminal error: ${r.message}]`)}catch(e){n.writeln(`\r\n[terminal error: ${e instanceof Error?e.message:String(e)}]`)}}writeTerminalOutput(e,t,n){if(!n){e.write(t);return}this.suppressTerminalInput=!0,e.reset(),e.write(`\x1Bc`+t,()=>{this.suppressTerminalInput=!1})}fitAndNotify(){let e=this.fitTerminal();e!==void 0&&this.send({type:`resize`,...e})}fitTerminal(){if(this.fitAddon===void 0||this.terminal===void 0)return;let e=kN(this.fitAddon.proposeDimensions());if(e!==void 0)return this.fitAddon.fit(),e}measureTerminalSize(){let e=this.fitTerminal();if(e!==void 0)return e;let t=this.terminalHostElement();if(this.terminal!==void 0||t===void 0)return;let n=new re(wN(this)),r=new ie;n.loadAddon(r),n.open(t);let i=kN(r.proposeDimensions());return n.dispose(),i}terminalHostElement(){let e=this.terminalHost;return e instanceof HTMLDivElement?e:void 0}applyTerminalTheme(){this.syncTerminalBackground(),this.terminal!==void 0&&(this.terminal.options.theme=TN(this))}syncTerminalBackground(){let e=DN(this.bgOpacity),t=ON(EN(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(mN,t),this.style.setProperty(hN,`${String(e)}%`)}sendTerminalInput(e){let t=SN(e);t!==``&&this.send({type:`input`,data:t})}sendSoftKeyInput(e,t){this.copySnapshot===void 0&&(this.sendTerminalInput(e),t.refocus&&this.focusTerminal())}focusTerminal(){let e=this.terminal;e!==void 0&&(e.focus(),requestAnimationFrame(()=>{e.focus()}))}send(e){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.terminalReconnectTimer!==void 0&&(window.clearTimeout(this.terminalReconnectTimer),this.terminalReconnectTimer=void 0),this.terminalReconnectDelay=dN;let e=this.socket;this.socket=void 0,e?.close(),this.terminal?.dispose(),this.terminal=void 0,this.fitAddon=void 0,this.copySnapshot=void 0,this.copyStatus=void 0}renderCommandRunNotice(){let e=this.selectedCommandRun();if(e===void 0)return null;let t=this.selectedTerminalInfo();if(yN(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
5985
|
+
`}};B([x({attribute:!1})],oN.prototype,`modes`,void 0),B([x({type:Boolean})],oN.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],oN.prototype,`onInput`,void 0),oN=B([b(`terminal-soft-keys`)],oN);function sN(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>iN}var cN=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>CN,terminalBackgroundWithOpacity:()=>kN}),lN={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},uN={cols:100,rows:30},dN=1e3,fN=500,pN=5e3,mN=1.6,hN=`--pi-terminal-effective-bg`,gN=`--pi-terminal-ui-opacity`,Z=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.autoStart=!1,this.fontSize=13,this.bgOpacity=100,this.onSelectTerminal=()=>void 0,this.terminals=[],this.commandRuns=[],this.loading=!1,this.visible=!1,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.defaultSoftKeysEnvironment=!1,this.softKeysEnabled=KM(),this.suppressTerminalInput=!1,this.terminalReconnectDelay=fN,this.softKeysDefaultEnvironmentMedia=WM(),this.softKeysPreferenceStored=qM(),this.onSoftKeysDefaultEnvironmentChange=()=>{this.syncDefaultSoftKeysEnvironment()}}connectedCallback(){super.connectedCallback(),this.syncTerminalBackground(),this.syncDefaultSoftKeysEnvironment(),this.softKeysDefaultEnvironmentMedia?.addEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.themeObserver=new MutationObserver(()=>{this.applyTerminalTheme()}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`,`style`,`data-theme`]})}firstUpdated(){this.intersectionObserver=new IntersectionObserver(e=>{this.visible=e[0]?.isIntersecting===!0}),this.intersectionObserver.observe(this)}disconnectedCallback(){this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.themeObserver?.disconnect(),this.themeObserver=void 0,this.softKeysDefaultEnvironmentMedia?.removeEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.updateCommandRunPolling(!1),this.disposeTerminalView(),super.disconnectedCallback()}syncDefaultSoftKeysEnvironment(){let e=GM(this.softKeysDefaultEnvironmentMedia),t=this.softKeysEnabled;this.defaultSoftKeysEnvironment=e,this.softKeysPreferenceStored||(this.softKeysEnabled=e),this.softKeysEnabled!==t&&this.scheduleFitAndNotify()}scheduleFitAndNotify(){this.updateComplete.then(()=>{this.fitAndNotify()})}willUpdate(e){e.has(`bgOpacity`)&&this.syncTerminalBackground();let t=this.workspace===void 0?void 0:JSON.stringify([this.machineId,this.workspace.path]);if(t!==this.observedWorkspaceScope){this.observedWorkspaceScope=t,this.loadedCwd=void 0,this.autoStartConsumedCwd=void 0,this.terminals=[],this.commandRuns=[],this.selectedId=void 0,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.updateCommandRunPolling(!1),this.disposeTerminalView();return}if(e.has(`selectedTerminalId`)){if(e.get(`selectedTerminalId`)!==void 0&&this.selectedTerminalId===void 0){this.loadedCwd=void 0,this.selectTerminalIdInView(void 0);return}this.applyRequestedTerminalSelection()}}updated(e){this.visible?this.hasPendingCommandRuns()&&this.updateCommandRunPolling(!0):this.updateCommandRunPolling(!1),this.loadVisibleWorkspaceTerminals(),e.has(`selectedTerminalId`)&&this.shouldReloadForRequestedTerminal()&&this.loadTerminals(),e.has(`fontSize`)&&this.terminal!==void 0&&(this.terminal.options.fontSize=this.fontSize,this.fitAndNotify()),e.has(`bgOpacity`)&&this.applyTerminalTheme(),this.ensureTerminalView()}loadVisibleWorkspaceTerminals(){let e=this.workspace?.path;!this.visible||e===void 0||e===this.loadedCwd||(this.loadedCwd=e,this.loadTerminals())}async loadTerminals(){this.loading=!0,this.error=void 0;try{let e=this.workspace;if(e===void 0)return;let t=this.consumeAutoStart(),[n,r]=await Promise.all([gs.terminals(e.projectId,e.id,this.machineId),gs.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId)]);this.terminals=n,this.commandRuns=r,this.selectPreferredLoadedTerminal({replaceUrl:!0}),this.updateCommandRunPolling(this.hasPendingCommandRuns(r)),n.length===0&&t&&await this.startTerminal()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}}applyRequestedTerminalSelection(){this.selectedTerminalId!==void 0&&!this.terminals.some(e=>e.id===this.selectedTerminalId)||this.selectPreferredLoadedTerminal({replaceUrl:!0})}consumeAutoStart(){let e=this.workspace?.path;return!this.autoStart||e===void 0||this.autoStartConsumedCwd===e?!1:(this.autoStartConsumedCwd=e,!0)}shouldReloadForRequestedTerminal(){let e=this.workspace?.path;return this.visible&&e!==void 0&&e===this.loadedCwd&&this.selectedTerminalId!==void 0&&!this.loading&&!this.terminals.some(e=>e.id===this.selectedTerminalId)}selectPreferredLoadedTerminal(e){let t=Jm(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=Ym(this.terminals)),this.selectTerminalIdInView(t?.id),(t?.id!==this.selectedTerminalId||t===void 0&&this.selectedTerminalId!==void 0)&&this.onSelectTerminal(t?.id,{replace:e?.replaceUrl===!0})}selectTerminalIdInView(e){this.selectedId!==e&&(this.selectedId=e,this.disposeTerminalView())}async startTerminal(){if(this.workspace!==void 0){this.error=void 0;try{let e=this.measureTerminalSize()??uN,t=await gs.startTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=[...this.terminals,t],this.selectTerminal(t.id)}catch(e){this.error=e instanceof Error?e.message:String(e)}}}async closeTerminal(e,t){t.stopPropagation();try{if(this.workspace===void 0)return;await gs.closeTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);let t=this.terminals.filter(t=>t.id!==e);if(this.terminals=t,this.selectedId===e||this.selectedTerminalId===e){let e=Ym(t)?.id;this.selectTerminalIdInView(e),this.onSelectTerminal(e,{replace:!0})}}catch(e){this.error=e instanceof Error?e.message:String(e)}}selectTerminal(e){this.selectedId!==e&&this.selectTerminalIdInView(e),this.onSelectTerminal(e)}selectedTerminalInfo(){return this.terminals.find(e=>e.id===this.selectedId)}selectedCommandRun(){let e=this.selectedTerminalInfo()?.commandRunId;if(e!==void 0)return this.commandRuns.find(t=>t.id===e)}async loadCommandRuns(){let e=this.workspace;if(e!==void 0)try{let t=await gs.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&bN(t))),this.updateCommandRunPolling(this.hasPendingCommandRuns(t))}catch(e){this.error=e instanceof Error?e.message:String(e)}}updateCommandRunPolling(e){if(e&&this.commandRunPollTimer===void 0){this.commandRunPollTimer=window.setInterval(()=>{this.loadCommandRuns()},dN);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(bN)}async cancelCommandRun(e){if(!(!bN(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await gs.cancelCommandRun(e.id,this.machineId),await this.loadCommandRuns()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.cancellingRunIds=this.cancellingRunIds.filter(t=>t!==e.id)}}}async continueTerminal(e){if(!(this.workspace===void 0||this.continuingTerminalIds.includes(e))){this.error=void 0,this.continuingTerminalIds=[...this.continuingTerminalIds,e];try{let t=await gs.continueTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=this.terminals.map(n=>n.id===e?t:n),this.socket===void 0&&this.disposeTerminalView(),this.fitAndNotify(),this.terminal?.focus()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.continuingTerminalIds=this.continuingTerminalIds.filter(t=>t!==e)}}}ensureTerminalView(){let e=this.workspace,t=this.terminalHostElement();if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||t===void 0||e===void 0)return;let n=new re(TN(this)),r=new ie;n.loadAddon(r),n.open(t),this.terminal=n,this.fitAddon=r,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(t),n.onData(e=>{this.suppressTerminalInput||this.copySnapshot!==void 0||this.sendTerminalInput(e)});let i=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,n,i),requestAnimationFrame(()=>{this.fitAndNotify()}),n.focus()}connectSocket(e,t,n,r,i){let a=Ts(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.socket===a&&(this.terminalReconnectDelay=fN,this.fitAndNotify())}),a.addEventListener(`message`,e=>{this.handleSocketMessage(e.data,n,r)}),a.addEventListener(`close`,()=>{if(this.socket!==a||(this.socket=void 0,this.terminals.some(e=>e.id===n&&e.exited)))return;this.terminalReconnectTimer!==void 0&&window.clearTimeout(this.terminalReconnectTimer);let o=this.terminalReconnectDelay;this.terminalReconnectDelay=Math.min(this.terminalReconnectDelay*mN,pN),this.terminalReconnectTimer=window.setTimeout(()=>{this.terminalReconnectTimer=void 0,!(this.socket!==void 0||this.terminals.some(e=>e.id===n&&e.exited))&&this.connectSocket(e,t,n,r,i)},o)})}async handleSocketMessage(e,t,n){try{let r=SN(await wN(e));r.type===`output`&&this.writeTerminalOutput(n,r.data,r.replay===!0),r.type===`exit`&&(n.writeln(`\r\n[process exited${r.exitCode===void 0?``:` with code ${String(r.exitCode)}`}]`),this.terminals=this.terminals.map(e=>e.id===t?{...e,exited:!0,...r.exitCode===void 0?{}:{exitCode:r.exitCode}}:e),this.loadCommandRuns()),r.type===`error`&&n.writeln(`\r\n[terminal error: ${r.message}]`)}catch(e){n.writeln(`\r\n[terminal error: ${e instanceof Error?e.message:String(e)}]`)}}writeTerminalOutput(e,t,n){if(!n){e.write(t);return}this.suppressTerminalInput=!0,e.reset(),e.write(`\x1Bc`+t,()=>{this.suppressTerminalInput=!1})}fitAndNotify(){let e=this.fitTerminal();e!==void 0&&this.send({type:`resize`,...e})}fitTerminal(){if(this.fitAddon===void 0||this.terminal===void 0)return;let e=AN(this.fitAddon.proposeDimensions());if(e!==void 0)return this.fitAddon.fit(),e}measureTerminalSize(){let e=this.fitTerminal();if(e!==void 0)return e;let t=this.terminalHostElement();if(this.terminal!==void 0||t===void 0)return;let n=new re(TN(this)),r=new ie;n.loadAddon(r),n.open(t);let i=AN(r.proposeDimensions());return n.dispose(),i}terminalHostElement(){let e=this.terminalHost;return e instanceof HTMLDivElement?e:void 0}applyTerminalTheme(){this.syncTerminalBackground(),this.terminal!==void 0&&(this.terminal.options.theme=EN(this))}syncTerminalBackground(){let e=ON(this.bgOpacity),t=kN(DN(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(hN,t),this.style.setProperty(gN,`${String(e)}%`)}sendTerminalInput(e){let t=CN(e);t!==``&&this.send({type:`input`,data:t})}sendSoftKeyInput(e,t){this.copySnapshot===void 0&&(this.sendTerminalInput(e),t.refocus&&this.focusTerminal())}focusTerminal(){let e=this.terminal;e!==void 0&&(e.focus(),requestAnimationFrame(()=>{e.focus()}))}send(e){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.terminalReconnectTimer!==void 0&&(window.clearTimeout(this.terminalReconnectTimer),this.terminalReconnectTimer=void 0),this.terminalReconnectDelay=fN;let e=this.socket;this.socket=void 0,e?.close(),this.terminal?.dispose(),this.terminal=void 0,this.fitAddon=void 0,this.copySnapshot=void 0,this.copyStatus=void 0}renderCommandRunNotice(){let e=this.selectedCommandRun();if(e===void 0)return null;let t=this.selectedTerminalInfo();if(bN(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
5984
5986
|
<section class="command-run-notice running">
|
|
5985
5987
|
<div>
|
|
5986
5988
|
<strong>${e.title}</strong>
|
|
@@ -5992,13 +5994,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5992
5994
|
`}if(t?.exited===!0){let n=this.continuingTerminalIds.includes(t.id);return g`
|
|
5993
5995
|
<section class=${`command-run-notice ${e.status}`}>
|
|
5994
5996
|
<div>
|
|
5995
|
-
<strong>${
|
|
5997
|
+
<strong>${xN(e)}</strong>
|
|
5996
5998
|
<p>Output is preserved. Continue in a shell to inspect or run follow-up commands.</p>
|
|
5997
5999
|
<code>${e.command}</code>
|
|
5998
6000
|
</div>
|
|
5999
6001
|
<button ?disabled=${n} @click=${()=>{this.continueTerminal(t.id)}}>${n?`Starting shell…`:`Continue in shell`}</button>
|
|
6000
6002
|
</section>
|
|
6001
|
-
`}return null}enterCopyMode(){this.copySnapshot===void 0&&this.captureCopySnapshot()}refreshCopyMode(){this.copySnapshot!==void 0&&this.captureCopySnapshot()}captureCopySnapshot(){let e=this.terminal;if(e===void 0)return;let t=
|
|
6003
|
+
`}return null}enterCopyMode(){this.copySnapshot===void 0&&this.captureCopySnapshot()}refreshCopyMode(){this.copySnapshot!==void 0&&this.captureCopySnapshot()}captureCopySnapshot(){let e=this.terminal;if(e===void 0)return;let t=kM(e.buffer.active,e.cols,{theme:e.options.theme,drawBoldTextInBrightColors:e.options.drawBoldTextInBrightColors});this.copySnapshot=t,this.copyStatus=void 0,e.blur(),this.updateComplete.then(()=>{let n=this.terminalCopySelector;if(n==null)return;let r=Math.max(0,t.physicalLineCount-e.rows),i=Math.min(r,t.viewportLine);n.scrollTop=(r===0?0:i/r)*Math.max(0,n.scrollHeight-n.clientHeight),this.syncCopySnapshotScroll()})}exitCopyMode(){this.copySnapshot!==void 0&&(this.copySnapshot=void 0,this.copyStatus=void 0)}syncCopySnapshotScroll(){let e=this.terminalCopySelector,t=this.terminalCopyContent;if(e==null||t==null)return;let n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.max(0,t.scrollHeight-t.clientHeight),i=Math.max(0,e.scrollWidth-e.clientWidth),a=Math.max(0,t.scrollWidth-t.clientWidth);t.scrollTop=_N(e.scrollTop,n,r),t.scrollLeft=_N(e.scrollLeft,i,a)}async copyAllSnapshotText(){let e=this.copySnapshot?.text??``;if(e===``){this.copyStatus=`No terminal output to copy.`;return}this.copyStatus=await uC(e)?`Copied all terminal output.`:`Unable to copy terminal output.`}renderCopyModeToggle(){if(this.selectedId===void 0)return null;let e=this.copySnapshot!==void 0;return g`
|
|
6002
6004
|
<button
|
|
6003
6005
|
type="button"
|
|
6004
6006
|
class=${e?`copy-mode-toggle selected`:`copy-mode-toggle`}
|
|
@@ -6021,7 +6023,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6021
6023
|
${this.copyToolbarReplacesSoftKeys()?null:this.renderCopyModeToolbar()}
|
|
6022
6024
|
<div class="terminal-copy-layers">
|
|
6023
6025
|
<pre class="terminal-copy-content" aria-hidden="true">${e.lines.map((e,t)=>g`${t===0?null:`
|
|
6024
|
-
`}${e.runs.map(e=>g`<span style=${
|
|
6026
|
+
`}${e.runs.map(e=>g`<span style=${CM(yN(e.style))}>${e.text}</span>`)}`)}</pre>
|
|
6025
6027
|
<textarea
|
|
6026
6028
|
class="terminal-copy-selector"
|
|
6027
6029
|
readonly
|
|
@@ -6036,7 +6038,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6036
6038
|
></textarea>
|
|
6037
6039
|
</div>
|
|
6038
6040
|
</section>
|
|
6039
|
-
`}selectedTerminalAcceptsInput(){let e=this.selectedTerminalInfo();return e!==void 0&&!e.exited}copyToolbarReplacesSoftKeys(){return this.copySnapshot!==void 0&&this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}renderTerminalAccessoryBar(){return this.copySnapshot===void 0?this.shouldShowSoftKeys()?this.renderSoftKeys():null:this.copyToolbarReplacesSoftKeys()?this.renderCopyModeToolbar():null}shouldShowSoftKeys(){return this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}shouldShowSoftKeysToggle(){return this.copySnapshot===void 0&&this.selectedTerminalAcceptsInput()}toggleSoftKeys(){this.copySnapshot===void 0&&(this.softKeysEnabled=!this.softKeysEnabled,this.softKeysPreferenceStored=!0,
|
|
6041
|
+
`}selectedTerminalAcceptsInput(){let e=this.selectedTerminalInfo();return e!==void 0&&!e.exited}copyToolbarReplacesSoftKeys(){return this.copySnapshot!==void 0&&this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}renderTerminalAccessoryBar(){return this.copySnapshot===void 0?this.shouldShowSoftKeys()?this.renderSoftKeys():null:this.copyToolbarReplacesSoftKeys()?this.renderCopyModeToolbar():null}shouldShowSoftKeys(){return this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}shouldShowSoftKeysToggle(){return this.copySnapshot===void 0&&this.selectedTerminalAcceptsInput()}toggleSoftKeys(){this.copySnapshot===void 0&&(this.softKeysEnabled=!this.softKeysEnabled,this.softKeysPreferenceStored=!0,YM(this.softKeysEnabled),this.scheduleFitAndNotify())}renderSoftKeysToggle(){return this.shouldShowSoftKeysToggle()?g`
|
|
6040
6042
|
<button
|
|
6041
6043
|
type="button"
|
|
6042
6044
|
class=${this.softKeysEnabled?`soft-keys-toggle selected`:`soft-keys-toggle`}
|
|
@@ -6157,32 +6159,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6157
6159
|
.error { flex: 0 0 auto; margin: 0; padding: 8px; color: var(--pi-danger); border-bottom: 1px solid var(--pi-border); background: color-mix(in srgb, var(--pi-surface) var(--pi-terminal-ui-opacity, 100%), transparent); }
|
|
6158
6160
|
.muted { margin: 10px; color: var(--pi-muted); }
|
|
6159
6161
|
.xterm { height: 100%; }
|
|
6160
|
-
`}};B([x({attribute:!1})],Z.prototype,`workspace`,void 0),B([x()],Z.prototype,`machineId`,void 0),B([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),B([x({type:Boolean})],Z.prototype,`autoStart`,void 0),B([x({type:Number})],Z.prototype,`fontSize`,void 0),B([x({type:Number})],Z.prototype,`bgOpacity`,void 0),B([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),B([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),B([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),B([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),B([S()],Z.prototype,`terminals`,void 0),B([S()],Z.prototype,`commandRuns`,void 0),B([S()],Z.prototype,`selectedId`,void 0),B([S()],Z.prototype,`loading`,void 0),B([S()],Z.prototype,`error`,void 0),B([S()],Z.prototype,`visible`,void 0),B([S()],Z.prototype,`cancellingRunIds`,void 0),B([S()],Z.prototype,`continuingTerminalIds`,void 0),B([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),B([S()],Z.prototype,`softKeysEnabled`,void 0),B([S()],Z.prototype,`copySnapshot`,void 0),B([S()],Z.prototype,`copyStatus`,void 0),Z=B([b(`terminal-panel`)],Z);function
|
|
6162
|
+
`}};B([x({attribute:!1})],Z.prototype,`workspace`,void 0),B([x()],Z.prototype,`machineId`,void 0),B([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),B([x({type:Boolean})],Z.prototype,`autoStart`,void 0),B([x({type:Number})],Z.prototype,`fontSize`,void 0),B([x({type:Number})],Z.prototype,`bgOpacity`,void 0),B([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),B([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),B([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),B([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),B([S()],Z.prototype,`terminals`,void 0),B([S()],Z.prototype,`commandRuns`,void 0),B([S()],Z.prototype,`selectedId`,void 0),B([S()],Z.prototype,`loading`,void 0),B([S()],Z.prototype,`error`,void 0),B([S()],Z.prototype,`visible`,void 0),B([S()],Z.prototype,`cancellingRunIds`,void 0),B([S()],Z.prototype,`continuingTerminalIds`,void 0),B([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),B([S()],Z.prototype,`softKeysEnabled`,void 0),B([S()],Z.prototype,`copySnapshot`,void 0),B([S()],Z.prototype,`copyStatus`,void 0),Z=B([b(`terminal-panel`)],Z);function _N(e,t,n){return t<=0||n<=0?0:Math.min(1,Math.max(0,e/t))*n}function vN(e){return/^#[\da-f]{6}$/i.test(e)?`${e}80`:`color-mix(in srgb, ${e} 50%, transparent)`}function yN(e){let t=[e.underline?`underline`:void 0,e.strikethrough?`line-through`:void 0,e.overline?`overline`:void 0].filter(e=>e!==void 0).join(` `);return{color:e.invisible?`transparent`:e.dim?vN(e.foreground):e.foreground,backgroundColor:e.background,fontWeight:e.bold?`700`:void 0,fontStyle:e.italic?`italic`:void 0,textDecorationLine:t===``?void 0:t}}function bN(e){return e.status===`queued`||e.status===`running`}function xN(e){return e.status===`succeeded`?`Command succeeded${e.exitCode===void 0?``:` with exit code ${String(e.exitCode)}`}`:`Command failed${e.exitCode===void 0?``:` with exit code ${String(e.exitCode)}`}`}function SN(e){let t=JSON.parse(e);if(!MN(t))return{type:`error`,message:`Invalid terminal message`};let n=t;return n.type===`output`&&typeof n.data==`string`?{type:`output`,data:n.data,...typeof n.replay==`boolean`?{replay:n.replay}:{}}:n.type===`exit`?{type:`exit`,...typeof n.exitCode==`number`?{exitCode:n.exitCode}:{}}:n.type===`error`&&typeof n.message==`string`?{type:`error`,message:n.message}:{type:`error`,message:`Invalid terminal message`}}function CN(e){return e.replaceAll(`\x1B[I`,``).replaceAll(`\x1B[O`,``)}async function wN(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function TN(e){let t=lN;return e instanceof Z?{...t,fontSize:e.fontSize,theme:EN(e)}:{...t,theme:EN(e)}}function EN(e){let t=kN(DN(e,`--pi-terminal-bg`,`#05070a`),e instanceof Z?e.bgOpacity:100);return{...OM,background:t,foreground:DN(e,`--pi-terminal-text`,`#e6edf3`),cursor:DN(e,`--pi-accent`,`#58a6ff`),selectionBackground:DN(e,`--pi-terminal-selection`,`#264f78`)}}function DN(e,t,n){let r=getComputedStyle(e).getPropertyValue(t).trim();return r===``?n:r}function ON(e){return Math.max(0,Math.min(100,e))}function kN(e,t){let n=ON(t)/100;if(n>=1||e===`transparent`)return e;let r=/^#([\da-f]{3}|[\da-f]{6})$/iu.exec(e);if(r===null)return e;let i=r[1]??``,[a=`00`,o=`00`,s=`00`]=i.length===3?[i.charAt(0).repeat(2),i.charAt(1).repeat(2),i.charAt(2).repeat(2)]:[i.slice(0,2),i.slice(2,4),i.slice(4,6)];return`rgba(${String(parseInt(a,16))}, ${String(parseInt(o,16))}, ${String(parseInt(s,16))}, ${String(n)})`}function AN(e){if(!(e===void 0||!jN(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function jN(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function MN(e){return typeof e==`object`&&!!e}var NN=class extends y{constructor(...e){super(...e),this.machines=[],this.activityRailOpen=!1,this.canScrollLeft=!1,this.canScrollRight=!1,this.handleToggleActivityRail=e=>{e.stopPropagation();let t=e.currentTarget;typeof HTMLElement>`u`||!(t instanceof HTMLElement)||this.onToggleActivityRail?.(t)},this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){let e=PN(this.machines),t=FN(this.machine),n=LN(this.project),r=zN(this.workspace),i=VN(this.session);return g`
|
|
6161
6163
|
<nav class=${this.contextBarClass()} aria-label="Current location">
|
|
6162
6164
|
<span class="context-bar-label">Location</span>
|
|
6163
6165
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
6164
6166
|
${e?g`
|
|
6165
6167
|
<li class="context-item">
|
|
6166
|
-
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6168
|
+
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${IN(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
|
|
6167
6169
|
<span class="context-kind">Machine</span>
|
|
6168
6170
|
<span class="context-value">${t}</span>
|
|
6169
6171
|
</button>
|
|
6170
6172
|
</li>
|
|
6171
6173
|
`:null}
|
|
6172
6174
|
<li class="context-item">
|
|
6173
|
-
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6175
|
+
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${RN(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
|
|
6174
6176
|
<span class="context-kind">Project</span>
|
|
6175
6177
|
<span class="context-value">${n}</span>
|
|
6176
6178
|
</button>
|
|
6177
6179
|
</li>
|
|
6178
6180
|
<li class="context-item">
|
|
6179
|
-
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6181
|
+
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${BN(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
|
|
6180
6182
|
<span class="context-kind">Workspace</span>
|
|
6181
6183
|
<span class="context-value">${r}</span>
|
|
6182
6184
|
</button>
|
|
6183
6185
|
</li>
|
|
6184
6186
|
<li class="context-item">
|
|
6185
|
-
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6187
|
+
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${HN(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
|
|
6186
6188
|
<span class="context-kind">Session</span>
|
|
6187
6189
|
<span class="context-value">${i}</span>
|
|
6188
6190
|
</button>
|
|
@@ -6230,7 +6232,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6230
6232
|
.context-kind { display: none; }
|
|
6231
6233
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
6232
6234
|
button { cursor: pointer; }
|
|
6233
|
-
`}};B([x({attribute:!1})],
|
|
6235
|
+
`}};B([x({attribute:!1})],NN.prototype,`machines`,void 0),B([x({attribute:!1})],NN.prototype,`machine`,void 0),B([x({attribute:!1})],NN.prototype,`project`,void 0),B([x({attribute:!1})],NN.prototype,`workspace`,void 0),B([x({attribute:!1})],NN.prototype,`session`,void 0),B([x({attribute:!1})],NN.prototype,`refreshControl`,void 0),B([x({attribute:!1})],NN.prototype,`onOpenSection`,void 0),B([x({attribute:!1})],NN.prototype,`onShowActions`,void 0),B([x({type:Boolean})],NN.prototype,`activityRailOpen`,void 0),B([x({attribute:!1})],NN.prototype,`onToggleActivityRail`,void 0),B([C(`.context-items`)],NN.prototype,`contextItems`,void 0),B([S()],NN.prototype,`canScrollLeft`,void 0),B([S()],NN.prototype,`canScrollRight`,void 0),NN=B([b(`app-context-bar`)],NN);function PN(e){return e.length>1}function FN(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function IN(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function LN(e){return e?.name??`No project`}function RN(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function zN(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function BN(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function VN(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?`No session`:Lx(e.id)}function HN(e){return e===void 0?`No session selected`:e.path}var UN=class extends y{constructor(...e){super(...e),this.tabs=[],this.selectedView=`chat`,this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){let e=this.fallbackLabels();return g`
|
|
6234
6236
|
<div class=${this.frameClass()}>
|
|
6235
6237
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
6236
6238
|
${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
|
|
@@ -6269,12 +6271,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6269
6271
|
.tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
|
|
6270
6272
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
6271
6273
|
}
|
|
6272
|
-
`}};B([x({attribute:!1})],
|
|
6274
|
+
`}};B([x({attribute:!1})],UN.prototype,`tabs`,void 0),B([x({attribute:!1})],UN.prototype,`selectedView`,void 0),B([x({attribute:!1})],UN.prototype,`onSelect`,void 0),B([C(`.mobile-tabs`)],UN.prototype,`mobileTabs`,void 0),B([S()],UN.prototype,`canScrollLeft`,void 0),B([S()],UN.prototype,`canScrollRight`,void 0),UN=B([b(`app-mobile-main-tabs`)],UN);var WN=class extends y{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle=``,this.actionMenuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has(`machines`)&&this.openActionsMachineId!==void 0&&!this.machines.some(e=>e.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){let e=this.switcherButton();return e!==null&&await this.openMenuAndFocusOption(e)}render(){let e=this.selectedMachine();if(e===void 0)return null;let t=GN(e,this.statuses),n=e.name;return g`
|
|
6273
6275
|
<div class="machine-switcher">
|
|
6274
6276
|
<button
|
|
6275
6277
|
type="button"
|
|
6276
6278
|
class="machine-switcher-button"
|
|
6277
|
-
title=${
|
|
6279
|
+
title=${qN(e)}
|
|
6278
6280
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
6279
6281
|
aria-expanded=${String(this.open)}
|
|
6280
6282
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
@@ -6285,7 +6287,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6285
6287
|
<span class="machine-switcher-kicker">Machine</span>
|
|
6286
6288
|
<span class="machine-switcher-label">${n}</span>
|
|
6287
6289
|
</span>
|
|
6288
|
-
<span class=${`machine-status ${t}`}>${
|
|
6290
|
+
<span class=${`machine-status ${t}`}>${KN(t)}</span>
|
|
6289
6291
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
6290
6292
|
</button>
|
|
6291
6293
|
${this.open?g`
|
|
@@ -6294,18 +6296,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6294
6296
|
</div>
|
|
6295
6297
|
`:null}
|
|
6296
6298
|
</div>
|
|
6297
|
-
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=
|
|
6299
|
+
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=GN(e,this.statuses),r=zb(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
|
|
6298
6300
|
<div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
|
|
6299
6301
|
<button
|
|
6300
6302
|
type="button"
|
|
6301
6303
|
class="machine-option-main"
|
|
6302
|
-
title=${
|
|
6304
|
+
title=${qN(e)}
|
|
6303
6305
|
data-machine-id=${e.id}
|
|
6304
6306
|
@click=${()=>{this.select(e)}}
|
|
6305
6307
|
@keydown=${e=>{this.handleMachineOptionKeydown(e)}}
|
|
6306
6308
|
>
|
|
6307
6309
|
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
6308
|
-
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${
|
|
6310
|
+
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${KN(n)}</small>
|
|
6309
6311
|
</button>
|
|
6310
6312
|
${r?g`
|
|
6311
6313
|
<div class="machine-option-actions">
|
|
@@ -6325,7 +6327,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6325
6327
|
</div>
|
|
6326
6328
|
`:null}
|
|
6327
6329
|
</div>
|
|
6328
|
-
`}renderActivity(e){let t=
|
|
6330
|
+
`}renderActivity(e){let t=GN(e,this.statuses);if(t===`offline`||t===`error`)return;let n=Xl(this.activities[e.id]);return Sb(n,n===`terminal`?`Machine terminal active`:`Machine active`)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`Machine: ${e.name}. Switch machine.`}switcherButton(){return this.renderRoot.querySelector(`.machine-switcher-button`)}handleSwitcherButtonKeydown(e){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key===`Escape`&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key===`ArrowUp`){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key===`ArrowDown`){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key===`Home`){this.focusIndexedMachineOption(0,e);return}if(e.key===`End`){this.focusIndexedMachineOption(-1,e);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key===`ArrowLeft`||e.key===`Escape`)&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=JN(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){let e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=JN(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){let e=this.renderRoot.querySelector(`.machine-option.selected .machine-option-main`),t=this.machineOptionButtons()[0],n=e??t;return n===void 0?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}focusRelativeMachineOption(e,t,n){n.preventDefault(),n.stopPropagation();let r=this.machineOptionButtons();if(r.length===0||!(e instanceof HTMLElement))return;let i=r.indexOf(e);i<0||this.focusMachineOptionAt(i+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){let t=this.machineOptionButtons(),n=t[Math.min(Math.max(e,0),t.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(`.machine-option-main`))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=vb(t,{constrainTo:`viewport`}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}static{this.styles=h`
|
|
6329
6331
|
:host { min-width: 0; display: block; }
|
|
6330
6332
|
.machine-switcher { min-width: 0; }
|
|
6331
6333
|
.machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
|
|
@@ -6358,10 +6360,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6358
6360
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
6359
6361
|
.machine-option-actions-panel button.danger:hover, .machine-option-actions-panel button.danger:focus-visible { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
6360
6362
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
6361
|
-
`}};B([x({attribute:!1})],
|
|
6363
|
+
`}};B([x({attribute:!1})],WN.prototype,`machines`,void 0),B([x({attribute:!1})],WN.prototype,`selected`,void 0),B([x({attribute:!1})],WN.prototype,`statuses`,void 0),B([x({attribute:!1})],WN.prototype,`activities`,void 0),B([x({attribute:!1})],WN.prototype,`onSelect`,void 0),B([x({attribute:!1})],WN.prototype,`onRemove`,void 0),B([x({attribute:!1})],WN.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],WN.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],WN.prototype,`open`,void 0),B([S()],WN.prototype,`menuStyle`,void 0),B([S()],WN.prototype,`openActionsMachineId`,void 0),B([S()],WN.prototype,`actionMenuStyle`,void 0),WN=B([b(`machine-switcher`)],WN);function GN(e,t){return t[e.id]?.status??e.status??`unknown`}function KN(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function qN(e){return e.baseUrl??e.name}function JN(e){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let t=e.getBoundingClientRect(),n=Math.min(280,Math.max(0,window.innerWidth-16)),r=Math.min(Math.max(8,t.left),Math.max(8,window.innerWidth-8-n)),i=Math.max(0,window.innerHeight-t.bottom-8);return[`top: ${YN(t.bottom)};`,`left: ${YN(r)};`,`width: ${YN(n)};`,`max-height: ${YN(i)};`].join(` `)}function YN(e){return`${String(Math.round(e))}px`}var XN=[{id:`models`,label:`Models`},{id:`skills`,label:`Skills`},{id:`plugins`,label:`Plugins`}],Q=class extends y{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.projectSessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canReorderSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`Update and restart Pi-Web on this machine to delete archived sessions.`,this.cleanupUnavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.skillsEnabled=!1,this.pluginsEnabled=!1,this.projectStatisticsAvailable=!1}async focusSection(e){switch(await this.updateComplete,e){case`machines`:return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case`projects`:return await this.focusNavigableSection(this.projectList);case`workspaces`:return await this.focusNavigableSection(this.workspaceList);case`sessions`:return await this.focusNavigableSection(this.sessionList)}}render(){let e=this.version;return g`
|
|
6362
6364
|
<header>
|
|
6363
6365
|
<strong class="brand" aria-label=${e===void 0?`Pi WebUI`:`Pi WebUI version ${e}`}><span class="brand-symbol" aria-hidden="true">π</span><span>WebUI</span>${e===void 0?null:g`<span class="brand-version">v${e}</span>`}</strong>
|
|
6364
|
-
${
|
|
6366
|
+
${eP(this.machines)?g`
|
|
6365
6367
|
<machine-switcher
|
|
6366
6368
|
.machines=${this.machines}
|
|
6367
6369
|
.selected=${this.selectedMachine}
|
|
@@ -6378,7 +6380,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6378
6380
|
<button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
|
|
6379
6381
|
</div>
|
|
6380
6382
|
</header>
|
|
6381
|
-
${this.compact
|
|
6383
|
+
${this.compact&&eP(this.machines)?g`
|
|
6382
6384
|
<machine-list
|
|
6383
6385
|
.machines=${this.machines}
|
|
6384
6386
|
.selected=${this.selectedMachine}
|
|
@@ -6475,9 +6477,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6475
6477
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
6476
6478
|
></session-list>
|
|
6477
6479
|
<footer class="resource-underbar" aria-label="Resources">
|
|
6478
|
-
${
|
|
6480
|
+
${XN.map(e=>ZN(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
|
|
6479
6481
|
</footer>
|
|
6480
|
-
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=
|
|
6482
|
+
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=tP(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(nP(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
|
|
6481
6483
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
6482
6484
|
:host([compact]) { flex: 1 1 auto; }
|
|
6483
6485
|
header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -6509,12 +6511,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6509
6511
|
:host([compact]) workspace-list[collapsed],
|
|
6510
6512
|
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
6511
6513
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
6512
|
-
`}};B([x({attribute:!1})],Q.prototype,`machines`,void 0),B([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),B([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),B([x({attribute:!1})],Q.prototype,`projects`,void 0),B([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),B([x({attribute:!1})],Q.prototype,`workspaces`,void 0),B([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`sessions`,void 0),B([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),B([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),B([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),B([x({type:String})],Q.prototype,`version`,void 0),B([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),B([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),B([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),B([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),B([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReorderSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),B([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),B([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),B([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),B([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),B([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),B([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSessionBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProjectTree`,void 0),B([x({attribute:!1})],Q.prototype,`onPinProject`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinProject`,void 0),B([x({attribute:!1})],Q.prototype,`onShowProjectStatistics`,void 0),B([x({type:Boolean})],Q.prototype,`projectStatisticsAvailable`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReorderSession`,void 0),B([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),B([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),B([C(`machine-list`)],Q.prototype,`machineList`,void 0),B([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),B([C(`project-list`)],Q.prototype,`projectList`,void 0),B([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),B([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=B([b(`app-navigation-panel`)],Q);function
|
|
6513
|
-
<button type="button" ?disabled=${!
|
|
6514
|
-
${
|
|
6514
|
+
`}};B([x({attribute:!1})],Q.prototype,`machines`,void 0),B([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),B([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),B([x({attribute:!1})],Q.prototype,`projects`,void 0),B([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),B([x({attribute:!1})],Q.prototype,`workspaces`,void 0),B([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`sessions`,void 0),B([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),B([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),B([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),B([x({type:String})],Q.prototype,`version`,void 0),B([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),B([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),B([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),B([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),B([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReorderSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),B([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),B([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),B([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),B([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),B([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),B([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSessionBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProjectTree`,void 0),B([x({attribute:!1})],Q.prototype,`onPinProject`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinProject`,void 0),B([x({attribute:!1})],Q.prototype,`onShowProjectStatistics`,void 0),B([x({type:Boolean})],Q.prototype,`projectStatisticsAvailable`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReorderSession`,void 0),B([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),B([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),B([C(`machine-list`)],Q.prototype,`machineList`,void 0),B([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),B([C(`project-list`)],Q.prototype,`projectList`,void 0),B([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),B([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=B([b(`app-navigation-panel`)],Q);function ZN(e,t,n,r){return g`
|
|
6515
|
+
<button type="button" ?disabled=${!QN(e.id,n,r)} title=${e.label} aria-label=${e.label} @click=${t}>
|
|
6516
|
+
${$N(e.id)}
|
|
6515
6517
|
<span>${e.label}</span>
|
|
6516
6518
|
</button>
|
|
6517
|
-
`}function
|
|
6519
|
+
`}function QN(e,t=!1,n=t){return e===`models`||e===`skills`&&t||e===`plugins`&&n}function $N(e){switch(e){case`models`:return _`
|
|
6518
6520
|
<svg class="resource-underbar-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
6519
6521
|
<rect x="4" y="4" width="16" height="16" rx="2"></rect>
|
|
6520
6522
|
<rect x="9" y="9" width="6" height="6"></rect>
|
|
@@ -6532,7 +6534,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6532
6534
|
<path d="M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0Z"></path>
|
|
6533
6535
|
<path d="M12 19v3"></path>
|
|
6534
6536
|
</svg>
|
|
6535
|
-
`}}function
|
|
6537
|
+
`}}function eP(e){return e.length>1}function tP(e,t){let n=rP(t);return n[n.indexOf(e)-1]}function nP(e,t){let n=rP(t);return n[n.indexOf(e)+1]??`chat`}function rP(e){return qv.filter(t=>t!==`machines`||eP(e))}var iP=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),aP=420,oP=4,sP=class extends y{constructor(...e){super(...e),this.side=`navigation`,this.collapsed=!1,this.resizable=!1,this.controls=``,this.resizeLabel=`Resize panel`,this.expandLabel=`Expand panel`,this.collapseLabel=`Collapse panel`,this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){let e=this.collapsed?this.expandLabel:this.collapseLabel;return g`
|
|
6536
6538
|
${this.renderResizeHandle()}
|
|
6537
6539
|
<button
|
|
6538
6540
|
type="button"
|
|
@@ -6562,7 +6564,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6562
6564
|
@dblclick=${e=>{this.onResizeDoubleClick(e)}}
|
|
6563
6565
|
@keydown=${e=>{this.onResizeKeyDown(e)}}
|
|
6564
6566
|
></div>
|
|
6565
|
-
`}resizeAriaValueNow(){return this.panelWidth===void 0?v:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=
|
|
6567
|
+
`}resizeAriaValueNow(){return this.panelWidth===void 0?v:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=oP)&&(t.moved=!0,this.commitPanelWidth(dy(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!iP.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=fy(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});n!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(n),this.onResizeEnd?.())}registerTapForReset(){let e=Date.now();if(e-this.lastTapAt<=aP){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){let e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return py(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(py(this.side,e,this.resizeConstraints()))}finishActiveResize(){let e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute(`resizing`,!1),this.onResizeEnd?.()}}resizeConstraints(){let e=ly(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
|
|
6566
6568
|
:host { position: relative; min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
|
|
6567
6569
|
:host([side="navigation"]) { grid-column: 2; }
|
|
6568
6570
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -6581,7 +6583,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6581
6583
|
@media (max-width: 760px) {
|
|
6582
6584
|
:host([side="navigation"]) { display: none; }
|
|
6583
6585
|
}
|
|
6584
|
-
`}};B([x({reflect:!0})],
|
|
6586
|
+
`}};B([x({reflect:!0})],sP.prototype,`side`,void 0),B([x({type:Boolean,reflect:!0})],sP.prototype,`collapsed`,void 0),B([x({type:Boolean})],sP.prototype,`resizable`,void 0),B([x({type:Number})],sP.prototype,`panelWidth`,void 0),B([x({type:Number})],sP.prototype,`minWidth`,void 0),B([x({type:Number})],sP.prototype,`maxWidth`,void 0),B([x()],sP.prototype,`controls`,void 0),B([x()],sP.prototype,`resizeLabel`,void 0),B([x()],sP.prototype,`expandLabel`,void 0),B([x()],sP.prototype,`collapseLabel`,void 0),B([x({attribute:!1})],sP.prototype,`onToggle`,void 0),B([x({attribute:!1})],sP.prototype,`onResizeStart`,void 0),B([x({attribute:!1})],sP.prototype,`onResize`,void 0),B([x({attribute:!1})],sP.prototype,`onResizeEnd`,void 0),B([x({attribute:!1})],sP.prototype,`onReset`,void 0),sP=B([b(`app-panel-edge-control`)],sP);var cP=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
|
|
6585
6587
|
<button
|
|
6586
6588
|
class="app-refresh-button"
|
|
6587
6589
|
title=${e}
|
|
@@ -6600,7 +6602,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6600
6602
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
6601
6603
|
.app-refresh-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 0; line-height: 1; cursor: pointer; touch-action: manipulation; -webkit-touch-callout: none; }
|
|
6602
6604
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
6603
|
-
`}};B([x({attribute:!1})],
|
|
6605
|
+
`}};B([x({attribute:!1})],cP.prototype,`onReload`,void 0),cP=B([b(`app-refresh-control`)],cP);var lP=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],uP=`file-manager`,dP=`browser`,fP=[...lP],pP=new Set(lP),mP=`pi-webui:activity-rail-order`;function hP(){return typeof localStorage>`u`?void 0:localStorage}function gP(e){return pP.has(e)}function _P(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===uP?`git-update-manager`:r;if(e!==dP){if(!gP(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===lP.length)return t;let r=[...t];if(!n.has(`git-update-manager`)){let e=r.indexOf(`terminal`);r.splice(e+1,0,`git-update-manager`)}return n.has(`info`)||r.push(`info`),r.length===lP.length?r:void 0}function vP(){try{let e=hP();if(e===void 0)return;let t=e.getItem(mP);return t===null?void 0:_P(JSON.parse(t))}catch{return}}function yP(e){try{let t=hP();if(t===void 0)return;t.setItem(mP,JSON.stringify(e))}catch{}}var bP=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function xP(e){return bP.includes(e)}function SP(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}var CP=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...fP],this.pluginItems=[],this.compactOpen=!1,this.onDesktopMediaChange=e=>{e.matches&&this.compactOpen&&this.onCloseCompact?.(),this.requestUpdate()},this.openTerminal=()=>{this.invokeCoreAction(this.onOpenTerminal)},this.openGitUpdateManager=()=>{this.invokeCoreAction(this.onOpenGitUpdateManager)},this.openTheme=()=>{this.invokeCoreAction(this.onOpenTheme)},this.openSystemPrompt=()=>{this.invokeCoreAction(this.onOpenSystemPrompt)},this.openHistory=()=>{this.invokeCoreAction(this.onOpenHistory)},this.openInfo=()=>{this.invokeCoreAction(this.onOpenInfo)},this.openSettings=()=>{this.invokeCoreAction(this.onOpenSettings)},this.openPluginActivity=(e,t)=>{this.closeCompactBeforeAction(),SP(t)&&this.onOpenPluginActivity?.(e,t)},this.closeCompact=()=>{this.onCloseCompact?.()},this.handleCompactBackdropMouseDown=e=>{e.target===e.currentTarget&&(e.preventDefault(),this.closeCompact())},this.handleCompactKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeCompact())},this.onDragStart=(e,t)=>{this.dragItem=e,t.dataTransfer!==null&&(t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,e)),requestAnimationFrame(()=>{this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.add(`dragging`)})},this.onDragEnd=e=>{this.dragItem=void 0,this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.remove(`dragging`),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)})},this.onRailDragOver=e=>{if(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`move`),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),t!==null&&t.dataset.railItem!==this.dragItem&&t.classList.add(`drag-over`)},this.onRailDrop=e=>{if(e.preventDefault(),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);if(t===null||t.dataset.railItem===this.dragItem){this.dragItem=void 0;return}let n=t.dataset.railItem;if(n===void 0||!xP(n)){this.dragItem=void 0;return}let r=[...this.railOrder],i=r.indexOf(this.dragItem),a=r.indexOf(n);if(i===-1||a===-1){this.dragItem=void 0;return}r.splice(i,1),r.splice(a,0,this.dragItem),this.railOrder=r,this.onRailOrderChange?.(r),this.dragItem=void 0},typeof window<`u`&&`matchMedia`in window&&(this.desktopMedia=window.matchMedia(Rv))}connectedCallback(){super.connectedCallback(),this.desktopMedia?.addEventListener(`change`,this.onDesktopMediaChange)}disconnectedCallback(){super.disconnectedCallback(),this.desktopMedia?.removeEventListener(`change`,this.onDesktopMediaChange)}updated(e){!e.has(`compactOpen`)||!this.compactOpen||this.isDesktopRailLayout()||this.renderRoot.querySelector(`.compact-rail-close`)?.focus()}isDesktopRailLayout(){return this.desktopMedia?.matches??!0}closeCompactBeforeAction(){this.isDesktopRailLayout()||this.onCloseCompact?.()}invokeCoreAction(e){this.closeCompactBeforeAction(),e?.()}resolveDragTarget(e){if(e===null||!(e instanceof HTMLElement))return null;let t=e.closest(`[data-rail-item]`);return t instanceof HTMLElement?t:null}dndProps(e){return{draggable:`true`,"data-rail-item":e}}renderReorderableButton(e){switch(e){case`terminal`:return this.renderTerminalButton();case`git-update-manager`:return this.renderGitUpdateManagerButton();case`theme`:return this.renderThemeButton();case`system-prompt`:return this.renderSystemPromptButton();case`history`:return this.renderHistoryButton();case`info`:return this.renderInfoButton()}}renderTerminalButton(){let e=this.dndProps(`terminal`),t=this.terminalCount>0?this.terminalCount:void 0,n=t===void 0?``:`${String(t)} active terminal${t===1?``:`s`}`;return g`
|
|
6604
6606
|
<button
|
|
6605
6607
|
type="button"
|
|
6606
6608
|
class="icon-button terminal-button"
|
|
@@ -6752,7 +6754,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6752
6754
|
${e.badge===void 0?v:g`<span class="rail-badge" aria-hidden="true">${e.badge}</span>`}
|
|
6753
6755
|
</button>
|
|
6754
6756
|
`}renderRailContents(){return g`
|
|
6755
|
-
${(this.railOrder.length===0?[...
|
|
6757
|
+
${(this.railOrder.length===0?[...fP]:this.railOrder).map(e=>this.renderReorderableButton(e))}
|
|
6756
6758
|
${this.pluginItems.length===0?v:g`
|
|
6757
6759
|
<div class="rail-plugin-separator" role="separator"></div>
|
|
6758
6760
|
${this.pluginItems.map(e=>this.renderPluginButton(e))}
|
|
@@ -6867,7 +6869,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6867
6869
|
.compact-rail-dialog { height: 100%; }
|
|
6868
6870
|
.compact-rail-dialog .rail { box-shadow: 8px 0 24px var(--pi-shadow); }
|
|
6869
6871
|
.compact-rail-close { margin-bottom: 2px; }
|
|
6870
|
-
`}};B([x({attribute:!1})],
|
|
6872
|
+
`}};B([x({attribute:!1})],CP.prototype,`onOpenTerminal`,void 0),B([x({attribute:!1})],CP.prototype,`onOpenGitUpdateManager`,void 0),B([x({attribute:!1})],CP.prototype,`onOpenTheme`,void 0),B([x({attribute:!1})],CP.prototype,`onOpenSystemPrompt`,void 0),B([x({attribute:!1})],CP.prototype,`onOpenHistory`,void 0),B([x({attribute:!1})],CP.prototype,`onOpenInfo`,void 0),B([x({attribute:!1})],CP.prototype,`onOpenSettings`,void 0),B([x({type:Number})],CP.prototype,`terminalCount`,void 0),B([x({type:Number})],CP.prototype,`gitUpdateManagerCount`,void 0),B([x({type:Boolean})],CP.prototype,`systemPromptEnabled`,void 0),B([x({type:Boolean})],CP.prototype,`historyEnabled`,void 0),B([x({attribute:!1})],CP.prototype,`railOrder`,void 0),B([x({attribute:!1})],CP.prototype,`onRailOrderChange`,void 0),B([x({attribute:!1})],CP.prototype,`pluginItems`,void 0),B([x({attribute:!1})],CP.prototype,`onOpenPluginActivity`,void 0),B([x({type:Boolean})],CP.prototype,`compactOpen`,void 0),B([x({attribute:!1})],CP.prototype,`onCloseCompact`,void 0),CP=B([b(`activity-rail`)],CP);var wP=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},TP=class extends y{constructor(...e){super(...e),this.close=()=>{this.onClose?.()},this.handleCancel=e=>{e.preventDefault(),this.close()},this.handleBackdropClick=e=>{e.target===e.currentTarget&&this.close()}}firstUpdated(){let e=this.nativeDialog;e?.isConnected===!0&&(e.showModal(),this.closeButton?.focus())}disconnectedCallback(){let e=this.nativeDialog;e?.open===!0&&e.close(),super.disconnectedCallback()}render(){let e=fg(this.activity,this.context,this.onReportError??wP);return g`
|
|
6871
6873
|
<dialog
|
|
6872
6874
|
class="plugin-activity-backdrop"
|
|
6873
6875
|
role="dialog"
|
|
@@ -6929,7 +6931,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6929
6931
|
header { padding-top: max(12px, env(safe-area-inset-top)); }
|
|
6930
6932
|
.plugin-activity-body { padding-bottom: max(12px, env(safe-area-inset-bottom)); }
|
|
6931
6933
|
}
|
|
6932
|
-
`}};B([x({attribute:!1})],
|
|
6934
|
+
`}};B([x({attribute:!1})],TP.prototype,`activity`,void 0),B([x({attribute:!1})],TP.prototype,`context`,void 0),B([x({attribute:!1})],TP.prototype,`onClose`,void 0),B([x({attribute:!1})],TP.prototype,`onReportError`,void 0),B([C(`dialog.plugin-activity-backdrop`)],TP.prototype,`nativeDialog`,void 0),B([C(`.plugin-activity-close`)],TP.prototype,`closeButton`,void 0),TP=B([b(`plugin-activity-dialog`)],TP);var EP=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.api=Ss,this.loadingStatus=!1,this.loadingDiff=!1,this.error=``,this.statusRequest=0,this.diffRequest=0,this.refresh=async()=>{let e=this.workspace;if(e===void 0)return;let t=this.machineId,n=this.selectedChange?.id,r=++this.statusRequest;this.diffRequest+=1,this.status=void 0,this.selectedDiff=void 0,this.loadingStatus=!0,this.loadingDiff=!1,this.error=``;try{let i=await this.api.gitStatus(e.projectId,e.id,t);if(r!==this.statusRequest||!this.isCurrentWorkspace(e,t))return;this.status=i,this.loadingStatus=!1,this.onStatusChange?.(i);let a=n===void 0?void 0:OP(i,n);this.selectedChange=a,a!==void 0&&await this.loadDiff(a,e,t)}catch(n){if(r!==this.statusRequest||!this.isCurrentWorkspace(e,t))return;this.status=void 0,this.selectedChange=void 0,this.selectedDiff=void 0,this.loadingStatus=!1,this.error=jP(n)}},this.selectChange=e=>{let t=this.workspace;if(t===void 0)return;let n=this.machineId;this.selectedChange=e,this.selectedDiff=void 0,this.error=``,this.loadDiff(e,t,n)},this.onViewportResize=()=>{this.bounds!==void 0&&(this.bounds=Ky(this.bounds,this.viewport()))},this.handleMovePointerDown=e=>{this.startPointerInteraction(`move`,e)},this.handleResizePointerDown=e=>{this.startPointerInteraction(`resize`,e)},this.handlePointerMove=e=>{let t=this.pointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY};this.bounds=t.operation===`move`?Wy(t.bounds,n,this.viewport()):Gy(t.bounds,n,this.viewport())},this.handlePointerUp=e=>{this.pointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishPointerInteraction())},this.handlePointerCancel=e=>{this.pointerInteraction?.pointerId===e.pointerId&&this.finishPointerInteraction()},this.close=()=>{this.finishPointerInteraction(),this.onClose?.()}}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),this.ensureWorkspaceScope()}willUpdate(){this.ensureWorkspaceScope()}disconnectedCallback(){this.finishPointerInteraction(),this.statusRequest+=1,this.diffRequest+=1,window.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}render(){return g`
|
|
6933
6935
|
<div class="git-update-manager-backdrop" role="dialog" aria-modal="true" aria-label="Git Update Manager">
|
|
6934
6936
|
<section class=${this.bounds===void 0?`git-update-manager-frame`:`git-update-manager-frame git-update-manager-frame-positioned`} style=${this.frameStyle()}>
|
|
6935
6937
|
<header class="git-update-manager-header">
|
|
@@ -6963,15 +6965,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6963
6965
|
></div>
|
|
6964
6966
|
</section>
|
|
6965
6967
|
</div>
|
|
6966
|
-
`}ensureWorkspaceScope(){let e=
|
|
6968
|
+
`}ensureWorkspaceScope(){let e=AP(this.workspace,this.machineId);e!==this.workspaceScope&&(this.workspaceScope=e,this.statusRequest+=1,this.diffRequest+=1,this.status=void 0,this.selectedChange=void 0,this.selectedDiff=void 0,this.loadingStatus=!1,this.loadingDiff=!1,this.error=``,e!==void 0&&this.isConnected&&this.refresh())}renderChangeList(){if(this.loadingStatus)return g`<p class="git-update-manager-empty">Loading changes…</p>`;let e=this.status;if(e===void 0)return g`<p class="git-update-manager-empty">Refresh to load Git changes.</p>`;if(!e.isGitRepo)return g`<p class="git-update-manager-empty">This workspace is not a Git repository.</p>`;let t=kl(e.files);return t.staged.length===0&&t.unstaged.length===0?g`<p class="git-update-manager-empty">No Git changes.</p>`:g`
|
|
6967
6969
|
${this.renderChangeGroup(`staged`,t.staged)}
|
|
6968
6970
|
${this.renderChangeGroup(`unstaged`,t.unstaged)}
|
|
6969
|
-
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=
|
|
6971
|
+
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=kP(e);return g`
|
|
6970
6972
|
<section class="git-update-manager-change-group" aria-label=${`${n} changes`}>
|
|
6971
6973
|
<h2>${n} (${String(t.length)})</h2>
|
|
6972
6974
|
${t.map(e=>this.renderChange(e))}
|
|
6973
6975
|
</section>
|
|
6974
|
-
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=Nl(e),r=Ml(e.state),i=
|
|
6976
|
+
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=Nl(e),r=Ml(e.state),i=kP(e.scope);return g`
|
|
6975
6977
|
<button
|
|
6976
6978
|
type="button"
|
|
6977
6979
|
class=${`git-update-manager-entry ${t?`selected`:``}`}
|
|
@@ -6983,13 +6985,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6983
6985
|
<span class="git-update-manager-path">${n}</span>
|
|
6984
6986
|
<span class="git-update-manager-scope">${i}</span>
|
|
6985
6987
|
</button>
|
|
6986
|
-
`}renderDiffPreview(){let e=this.selectedChange;if(e===void 0)return g`<p class="git-update-manager-empty">Select a Git change to review.</p>`;if(this.error!==``)return g`<p class="git-update-manager-empty">Could not load ${Nl(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${Nl(e)}…</p>`;let t=this.selectedDiff;return
|
|
6988
|
+
`}renderDiffPreview(){let e=this.selectedChange;if(e===void 0)return g`<p class="git-update-manager-empty">Select a Git change to review.</p>`;if(this.error!==``)return g`<p class="git-update-manager-empty">Could not load ${Nl(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${Nl(e)}…</p>`;let t=this.selectedDiff;return DP(),g`
|
|
6987
6989
|
<header class="git-update-manager-diff-header">
|
|
6988
6990
|
<strong>${Nl(e)}</strong>
|
|
6989
|
-
<small>${
|
|
6991
|
+
<small>${kP(e.scope)} · ${Ml(e.state)}${t.truncated?` · truncated`:``}</small>
|
|
6990
6992
|
</header>
|
|
6991
6993
|
<unified-diff-viewer .diff=${t.diff}></unified-diff-viewer>
|
|
6992
|
-
`}async loadDiff(e,t,n){let r=++this.diffRequest;this.loadingDiff=!0;try{let i=await this.api.gitDiff(t.projectId,t.id,{path:e.path,staged:e.scope===`staged`},n);if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=i,this.loadingDiff=!1,this.error=``}catch(i){if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=void 0,this.loadingDiff=!1,this.error=
|
|
6994
|
+
`}async loadDiff(e,t,n){let r=++this.diffRequest;this.loadingDiff=!0;try{let i=await this.api.gitDiff(t.projectId,t.id,{path:e.path,staged:e.scope===`staged`},n);if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=i,this.loadingDiff=!1,this.error=``}catch(i){if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=void 0,this.loadingDiff=!1,this.error=jP(i)}}startPointerInteraction(e,t){if(t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.git-update-manager-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=Ky(this.boundsFromFrame(r),this.viewport());n.setPointerCapture(t.pointerId),this.bounds=i,this.pointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}boundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}viewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}frameStyle(){let e=this.bounds;return e===void 0?``:`left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px;`}finishPointerInteraction(){let e=this.pointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.pointerInteraction=void 0}}isCurrentWorkspace(e,t){return this.workspace?.id===e.id&&this.workspace.projectId===e.projectId&&this.machineId===t}static{this.styles=h`
|
|
6993
6995
|
:host { position: fixed; inset: 0; z-index: 80; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
6994
6996
|
.git-update-manager-backdrop { width: 100%; height: 100dvh; display: grid; place-items: center; padding: 16px; background: rgba(0, 0, 0, .48); }
|
|
6995
6997
|
.git-update-manager-frame { position: relative; display: flex; flex-direction: column; width: min(calc(100vw - 32px), 1280px); height: min(calc(100vh - 32px), 880px); overflow: hidden; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 64px var(--pi-shadow-strong); }
|
|
@@ -7028,7 +7030,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7028
7030
|
.git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
|
|
7029
7031
|
.git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
|
|
7030
7032
|
}
|
|
7031
|
-
`}};B([x({attribute:!1})],TP.prototype,`onClose`,void 0),B([x({attribute:!1})],TP.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],TP.prototype,`workspace`,void 0),B([x()],TP.prototype,`machineId`,void 0),B([x({attribute:!1})],TP.prototype,`api`,void 0),B([S()],TP.prototype,`status`,void 0),B([S()],TP.prototype,`selectedChange`,void 0),B([S()],TP.prototype,`selectedDiff`,void 0),B([S()],TP.prototype,`loadingStatus`,void 0),B([S()],TP.prototype,`loadingDiff`,void 0),B([S()],TP.prototype,`error`,void 0),B([S()],TP.prototype,`bounds`,void 0),TP=B([b(`git-update-manager-panel`)],TP);function EP(){l_(()=>import(`./UnifiedDiffViewer-C99T12hF.js`),[],import.meta.url)}function DP(e,t){let n=kl(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function OP(e){return e===`staged`?`Staged`:`Unstaged`}function kP(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function AP(e){return e instanceof Error?e.message:String(e)}var jP=900*1e3,MP=750,NP=[1e3,3e3,8e3,15e3,3e4],PP={capture:!0},FP=`auto:on`,IP=`auto:off`,LP=`theme:`,RP=tl(`core:workspace.files`),zP=tl(`core:workspace.git`),BP=tl(`core:workspace.terminal`),VP=`workspace-memory`,HP=`workspace.memory`,UP=`workspace-memory:workspace.memory`,WP=`workspace-learned-skills`,GP=`workspace.learned-skills`,KP=`workspace-learned-skills:workspace.learned-skills`,qP=320,JP=2,YP=`(min-width: 1181px)`,XP=75,ZP=`Could not remember this model policy; this session still uses it.`,$=class extends y{constructor(...e){super(...e),this.state=Uc(),this.sessionUnread=new Xh({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 mm(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new hp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new tp,{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)}}),this.workspaces=new Sm(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new bm,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new Gl(()=>this.state,{workspaces:ms.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 $l(()=>this.state,e=>{this.setState(e)},{api:ms,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 Yc(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Qc(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Vl(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Ll(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new tu(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new ml(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new bl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new Dl(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new Cl(()=>this.state,e=>{this.setState(e)}),this.keyboard=new Qm,this.realtime=new yf,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Pm,this.terminalSelection=new qm,this.appShell=new zv(this),this.browserResume=new Hv({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new iy(this),this.panelResize=new cy(this),this.navigationSections=new ty(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=QP(),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=vg()??mg,this.activeThemeId=pg,this.isRefreshingApp=!1,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new wh({save:async(e,t)=>{let n=await hs.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 kh({remember:(e,t)=>hs.rememberCurrentModelPolicy(t,e.machineId),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=$y(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=sb(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=_P()??[...dP],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=ky(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=js(void 0),this.sessionWarningVisibility=ig(),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=Ky(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{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(jc(e));return}this.starterNotice=void 0;let i=this.state.selectedWorkspace?.id,a=R(this.state),o=this.starterModelPolicy,s=this.starterPlusModelPolicyInitializer();this.starterModelPolicySelectionSupported(a)&&s===void 0||((s===void 0?this.sessions.startSessionWithPrompt(e,t,n,r,this.starterModelPolicyStartSnapshot(),e=>{this.clearStarterModelPolicyAfterSuccessfulStart(e,i,o)}):this.sessions.startPlusSessionWithPrompt(e,t,n,r??`inline`,s,()=>void 0)).catch(e=>{i!==void 0&&this.publishStarterNotice(Mc(`start-failed`,`Could not start the session. ${wF(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`?oc(t):t.tier===void 0?{...t,mode:`tiered`}:ac(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(R(this.state));return}if(e===`exact`){let e=oc(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:ec(n);r!==void 0&&ic(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:ac(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||lc(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=ac(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}lc(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(oc(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(ac(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=ac(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,vP(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`?Wy(t.bounds,n,r):Gy(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=Zy(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=Qy(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=lg(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncStarterNotice()}updated(){this.committedChatIdentity=tF(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=og(this.sessionWarningVisibility,e===void 0?void 0:qc(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=eF(e,t);await this.updateComplete,!(!this.unreadConnected||tF(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);vF(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=pb(this.state.selectedProject?.name);this.windowTitleCleanup=mb(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=eF(e,t);return tF(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}connectedCallback(){super.connectedCallback(),this.synchronizeProjectCatalogPolling(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,PP),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},jP),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.finishTerminalModalPointerInteraction(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,PP),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(),super.disconnectedCallback()}setState(e){if(!_F(this.state,e))return;let t=this.state,n=nF(t),r=iF(t),i=rF(t);this.state={...this.state,...e},i!==rF(this.state)&&(this.starterModelPolicySelectionGeneration+=1),n!==nF(this.state)&&this.resetActiveModelPolicyDraft(),tF(t)!==tF(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),pF(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),mF(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let a=iF(this.state);a!==void 0&&a!==r&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=wy();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()])}schedulePiWebUiStatusRefresh(e=MP){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=>gF(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 Yo.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=js(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(wy(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?xF():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===``?xF():{selectedFilePath:rl(RP,`file`),selectedDiffPath:rl(zP,`diff`),selectedTerminalId:rl(BP,`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){Ty(e,{replace:!0}),il(RP,`file`,void 0,{replace:!0}),il(zP,`diff`,void 0,{replace:!0}),il(BP,`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=CF(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>=NP.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 DF(),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(),Ty({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(Im(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Im(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Ty(Lm(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){il(RP,`file`,e.selectedFilePath,{replace:!0}),il(zP,`diff`,e.selectedDiffPath,{replace:!0}),il(BP,`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)??Fm(e.id);if(await this.restoreRouteFor(Lm(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=SF(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Iy(e,{api:{runTerminalCommand:(e,n)=>gs.runTerminalCommand(e,n,t),listCommandRuns:e=>gs.listCommandRuns(e,t),getCommandRun:e=>gs.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((R(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:`core:workspace.terminal`,view:`core:workspace.terminal`},!1,{selectedTerminalId:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)){this.setState({error:`Machine not found for terminal command run`});return}this.openTerminal(n)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){il(BP,`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,Ay(e)}closeSettings(){this.settingsSection=void 0,Ay(void 0)}navigateSettings(e){this.settingsSection=e,Ay(e)}restoreSettingsRoute(){this.settingsSection=ky()}handleWorkspaceChange(e,t){let n=fF(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&(this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace());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();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace()}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 hs.sessionDefaultsV2(e.path,n):await hs.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&&!cF(o)?this.starterModelPolicy=tc(r):i?this.starterModelPolicy=s:this.starterModelPolicy=nc(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(Mc(`defaults-failed`,`Could not load this workspace's model defaults. ${wF(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 yf;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=>hF(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):bF(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 gs.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=yF(e),r=yF(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.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.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(){let e=this.state.selectedWorkspace;return g`
|
|
7033
|
+
`}};B([x({attribute:!1})],EP.prototype,`onClose`,void 0),B([x({attribute:!1})],EP.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],EP.prototype,`workspace`,void 0),B([x()],EP.prototype,`machineId`,void 0),B([x({attribute:!1})],EP.prototype,`api`,void 0),B([S()],EP.prototype,`status`,void 0),B([S()],EP.prototype,`selectedChange`,void 0),B([S()],EP.prototype,`selectedDiff`,void 0),B([S()],EP.prototype,`loadingStatus`,void 0),B([S()],EP.prototype,`loadingDiff`,void 0),B([S()],EP.prototype,`error`,void 0),B([S()],EP.prototype,`bounds`,void 0),EP=B([b(`git-update-manager-panel`)],EP);function DP(){l_(()=>import(`./UnifiedDiffViewer-CqMCpp0S.js`),[],import.meta.url)}function OP(e,t){let n=kl(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function kP(e){return e===`staged`?`Staged`:`Unstaged`}function AP(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function jP(e){return e instanceof Error?e.message:String(e)}var MP=900*1e3,NP=750,PP=[1e3,3e3,8e3,15e3,3e4],FP={capture:!0},IP=`auto:on`,LP=`auto:off`,RP=`theme:`,zP=tl(`core:workspace.files`),BP=tl(`core:workspace.git`),VP=tl(`core:workspace.terminal`),HP=`workspace-memory`,UP=`workspace.memory`,WP=`workspace-memory:workspace.memory`,GP=`workspace-learned-skills`,KP=`workspace.learned-skills`,qP=`workspace-learned-skills:workspace.learned-skills`,JP=320,YP=2,XP=`(min-width: 1181px)`,ZP=75,QP=`Could not remember this model policy; this session still uses it.`,$=class extends y{constructor(...e){super(...e),this.state=Uc(),this.sessionUnread=new Xh({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 mm(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new hp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new tp,{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)}}),this.workspaces=new Sm(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new bm,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new Gl(()=>this.state,{workspaces:ms.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 $l(()=>this.state,e=>{this.setState(e)},{api:ms,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 Yc(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Qc(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Vl(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Ll(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new tu(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new ml(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new bl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new Dl(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new Cl(()=>this.state,e=>{this.setState(e)}),this.keyboard=new Qm,this.realtime=new yf,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Pm,this.terminalSelection=new qm,this.appShell=new zv(this),this.browserResume=new Hv({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new iy(this),this.panelResize=new cy(this),this.navigationSections=new ty(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=$P(),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=vg()??mg,this.activeThemeId=pg,this.isRefreshingApp=!1,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new wh({save:async(e,t)=>{let n=await hs.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 kh({remember:(e,t)=>hs.rememberCurrentModelPolicy(t,e.machineId),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=$y(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=sb(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=vP()??[...fP],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=ky(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=js(void 0),this.sessionWarningVisibility=ig(),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=Ky(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{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(jc(e));return}this.starterNotice=void 0;let i=this.state.selectedWorkspace?.id,a=R(this.state),o=this.starterModelPolicy,s=this.starterPlusModelPolicyInitializer();this.starterModelPolicySelectionSupported(a)&&s===void 0||((s===void 0?this.sessions.startSessionWithPrompt(e,t,n,r,this.starterModelPolicyStartSnapshot(),e=>{this.clearStarterModelPolicyAfterSuccessfulStart(e,i,o)}):this.sessions.startPlusSessionWithPrompt(e,t,n,r??`inline`,s,()=>void 0)).catch(e=>{i!==void 0&&this.publishStarterNotice(Mc(`start-failed`,`Could not start the session. ${TF(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`?oc(t):t.tier===void 0?{...t,mode:`tiered`}:ac(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(R(this.state));return}if(e===`exact`){let e=oc(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:ec(n);r!==void 0&&ic(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:ac(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||lc(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=ac(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}lc(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(oc(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(ac(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=ac(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,yP(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`?Wy(t.bounds,n,r):Gy(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=Zy(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=Qy(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=lg(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncStarterNotice()}updated(){this.committedChatIdentity=nF(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=og(this.sessionWarningVisibility,e===void 0?void 0:qc(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=tF(e,t);await this.updateComplete,!(!this.unreadConnected||nF(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);yF(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=pb(this.state.selectedProject?.name);this.windowTitleCleanup=mb(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=tF(e,t);return nF(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}connectedCallback(){super.connectedCallback(),this.synchronizeProjectCatalogPolling(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,FP),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},MP),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.finishTerminalModalPointerInteraction(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,FP),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(),super.disconnectedCallback()}setState(e){if(!vF(this.state,e))return;let t=this.state,n=rF(t),r=aF(t),i=iF(t);this.state={...this.state,...e},i!==iF(this.state)&&(this.starterModelPolicySelectionGeneration+=1),n!==rF(this.state)&&this.resetActiveModelPolicyDraft(),nF(t)!==nF(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),mF(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),hF(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let a=aF(this.state);a!==void 0&&a!==r&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=wy();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()])}schedulePiWebUiStatusRefresh(e=NP){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=>_F(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 Yo.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=js(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(wy(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?SF():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===``?SF():{selectedFilePath:rl(zP,`file`),selectedDiffPath:rl(BP,`diff`),selectedTerminalId:rl(VP,`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){Ty(e,{replace:!0}),il(zP,`file`,void 0,{replace:!0}),il(BP,`diff`,void 0,{replace:!0}),il(VP,`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=wF(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>=PP.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 OF(),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(),Ty({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(Im(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Im(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Ty(Lm(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){il(zP,`file`,e.selectedFilePath,{replace:!0}),il(BP,`diff`,e.selectedDiffPath,{replace:!0}),il(VP,`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)??Fm(e.id);if(await this.restoreRouteFor(Lm(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=CF(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Iy(e,{api:{runTerminalCommand:(e,n)=>gs.runTerminalCommand(e,n,t),listCommandRuns:e=>gs.listCommandRuns(e,t),getCommandRun:e=>gs.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((R(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:`core:workspace.terminal`,view:`core:workspace.terminal`},!1,{selectedTerminalId:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)){this.setState({error:`Machine not found for terminal command run`});return}this.openTerminal(n)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){il(VP,`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,Ay(e)}closeSettings(){this.settingsSection=void 0,Ay(void 0)}navigateSettings(e){this.settingsSection=e,Ay(e)}restoreSettingsRoute(){this.settingsSection=ky()}handleWorkspaceChange(e,t){let n=pF(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&(this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace());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();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace()}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 hs.sessionDefaultsV2(e.path,n):await hs.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&&!lF(o)?this.starterModelPolicy=tc(r):i?this.starterModelPolicy=s:this.starterModelPolicy=nc(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(Mc(`defaults-failed`,`Could not load this workspace's model defaults. ${TF(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 yf;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=>gF(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):xF(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 gs.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=bF(e),r=bF(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.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.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(){let e=this.state.selectedWorkspace;return g`
|
|
7032
7034
|
<workspace-panel
|
|
7033
7035
|
id="workspace-panel"
|
|
7034
7036
|
.workspace=${e}
|
|
@@ -7075,7 +7077,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7075
7077
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
7076
7078
|
.onReset=${()=>{this.resetResizablePanel(`workspace`)}}
|
|
7077
7079
|
></app-panel-edge-control>
|
|
7078
|
-
`}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-JP-qP);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let t=e===`navigation`?`workspace`:`navigation`;return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>`u`||!(`matchMedia`in window)||window.matchMedia(YP).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||E(e,w.sessionsDeleteArchived)}get projectStatisticsAvailable(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.projectUsageStatistics)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReload)}canReorderSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReorder)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return Hf(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.workspaceFileSuggestions)}sessionModelPolicySupported(e=R(this.state)){return oF(this.state,e)}starterModelPolicySelectionSupported(e=R(this.state)){return sF(this.state,e)}handleStarterModelPolicyCapabilityChange(e,t){let n=R(t);if(R(e)!==n||sF(e,n)||!sF(t,n)||!this.shouldShowSessionStartScreen(t))return;let r=t.selectedWorkspace;r!==void 0&&this.loadStarterSessionDefaults(r)}starterModelPolicyPreferenceScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),cwd:e.path}}starterModelPolicyPreferenceScopeMatchesCurrentSelection(e){let t=this.starterModelPolicyPreferenceScope();return t?.machineId===e.machineId&&t.cwd===e.cwd}handleStarterModelPolicyConfirmed(e){let t={machineId:e.machineId,cwd:e.session.cwd},n=this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(t);n&&this.state.selectedSession?.id===e.session.id&&this.state.selectedSession.cwd===e.session.cwd?(this.starterModelPolicy=Zs(e.policy),this.starterModelPolicyPreferenceReadError=``,this.confirmedStarterModelPolicyUiScope=t,this.confirmedStarterModelPolicyUiGeneration=this.starterModelPolicySelectionGeneration):n&&(this.confirmedStarterModelPolicyUiScope!==void 0||this.confirmedStarterModelPolicyUiGeneration!==void 0)&&(this.confirmedStarterModelPolicyUiScope=void 0,this.confirmedStarterModelPolicyUiGeneration=void 0,this.requestUpdate()),this.confirmedStarterModelPolicyPreferenceWriter.write(t,e.session)}starterNoticeScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),workspaceId:e.id}}publishStarterNotice(e){let t=this.starterNoticeScope();t?.machineId!==e.scope.machineId||t.workspaceId!==e.scope.workspaceId||(this.starterNotice=e)}syncStarterNotice(){let e=this.starterNotice;e!==void 0&&(Pc(e,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)||(this.starterNotice=void 0))}starterModelPolicyPreferenceSupported(e){let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.sessionsModelPolicyDefaults)}persistStarterModelPolicyPreference(e){let t=this.starterModelPolicyPreferenceScope(),n=rc(e);t===void 0||n===void 0||!this.starterModelPolicyPreferenceSupported(t.machineId)||this.starterModelPolicyPreferenceWriter.write(t,n)}loadModelTierCatalog(e){let t=this.state.selectedWorkspace?.id,n=++this.modelTierCatalogSeq,r=this.performModelTierCatalogLoad(e,t,n);this.modelTierCatalogLoad={machineId:e,workspaceId:t,promise:r};let i=()=>{this.modelTierCatalogLoad?.promise===r&&(this.modelTierCatalogLoad=void 0)};return r.then(i,i),r}async performModelTierCatalogLoad(e,t,n){let r=()=>n===this.modelTierCatalogSeq&&R(this.state)===e&&this.state.selectedWorkspace?.id===t;this.modelTierCatalogLoading=!0,this.modelTierCatalogError=``;try{let t=await es.settings(e);if(!r())return;this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.completeStarterModelPolicyFromActiveTier()}catch(e){if(!r())return;this.modelTierCatalogError=wF(e)}finally{n===this.modelTierCatalogSeq&&(this.modelTierCatalogLoading=!1)}}ensureModelTierCatalog(e){if(this.selectedMachineModelTierCatalog()!==void 0)return Promise.resolve();let t=this.state.selectedWorkspace?.id,n=this.modelTierCatalogLoad;return n?.machineId===e&&n.workspaceId===t?n.promise:this.loadModelTierCatalog(e)}resetStarterModelPolicyForScopeChange(){this.starterSessionDefaultsSeq+=1,this.starterModelPolicySelectionGeneration+=1,this.starterModelPolicy=void 0,this.starterModelPolicyPreferenceReadError=``,this.starterNotice=void 0,this.modelTierCatalogError=``}resetModelTierCatalogForMachineChange(){this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogMachineId=void 0,this.modelTierCatalog=void 0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``}handleModelTiersSaved(e,t){R(this.state)===e&&(this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.modelTierCatalogError=``,this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogLoading=!1,this.completeStarterModelPolicyFromActiveTier(),iF(this.state)!==void 0&&this.sessions.loadModelPolicy())}completeStarterModelPolicyFromActiveTier(){let e=this.starterSessionDefaults,t=this.starterModelPolicy,n=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0||n===void 0)return;let r=dc(t,e,n);lF(t,r)||(this.starterModelPolicy=r)}selectedMachineModelTierCatalog(){if(this.modelTierCatalogMachineId===R(this.state))return this.modelTierCatalog}preloadActiveModelPolicyInputs(){this.sessions.loadModelPolicy(),this.ensureModelTierCatalog(R(this.state))}async prepareActiveModelPolicyDraft(){if(!this.sessionModelPolicySupported())return;let e=nF(this.state);if(e===void 0||aF(this.state)===void 0)return;let t=this.activeModelPolicyDraftForState(this.state);if(t!==void 0)return t;let n=[];if(this.state.modelPolicy===void 0&&n.push(this.sessions.loadModelPolicy()),this.selectedMachineModelTierCatalog()===void 0&&n.push(this.ensureModelTierCatalog(R(this.state))),await Promise.all(n),nF(this.state)!==e)return;let r=this.activeModelPolicyDraftForState(this.state);if(r!==void 0)return r;let i=this.selectedMachineModelTierCatalog(),a=aF(this.state);if(i===void 0||a===void 0)return;let o=this.state.modelPolicy?.policy,s;if(o!==void 0)s=Qs({policy:o,catalog:i});else if(a.mode===`exact`)s=Qs({liveResolved:a.resolved,catalog:i});else{let e=Qs({catalog:i});s=a.tier===void 0?{...e,mode:`tiered`}:ac(e,a.tier)}return this.activeModelPolicyDraftScope=e,this.activeModelPolicyDraft=s,s}activeModelPolicyDraftForState(e){return this.activeModelPolicyDraftScope===nF(e)?this.activeModelPolicyDraft:void 0}setActiveModelPolicyDraft(e){let t=nF(this.state);t!==void 0&&(this.activeModelPolicyDraftScope=t,this.activeModelPolicyDraft=e)}resetActiveModelPolicyDraft(){this.cancelActiveModelPolicyApply(),this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0}cancelActiveModelPolicyApply(){this.activeModelPolicyApplyGeneration+=1,this.activeModelPolicyApplyTimer!==void 0&&window.clearTimeout(this.activeModelPolicyApplyTimer),this.activeModelPolicyApplyTimer=void 0}scheduleActiveExactModelPolicyApply(){this.cancelActiveModelPolicyApply();let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e?.mode!==`exact`||!uc(e,t))return;let n=this.activeModelPolicyApplyGeneration;this.activeModelPolicyApplyTimer=window.setTimeout(()=>{n===this.activeModelPolicyApplyGeneration&&(this.activeModelPolicyApplyTimer=void 0,this.applyActiveModelPolicyDraft())},XP)}async applyActiveModelPolicyDraft(){let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e===void 0||!uc(e,t)||t===void 0)return;let n=lc(e,t);if(n===void 0)return;let r=this.activeModelPolicyDraftScope,i=this.state.modelPolicy;if(await this.sessions.saveModelPolicy(n),r!==nF(this.state)||this.activeModelPolicyDraft!==e)return;if(this.state.modelPolicyError!==void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}if(this.state.modelPolicy===i)return;let a=this.state.modelPolicy?.policy;if(a===void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}this.setActiveModelPolicyDraft(Qs({policy:a,catalog:t}))}policyThinkingOptions(e,t){let n=this.selectedMachineModelTierCatalog(),r=n?.models.find(t=>t.model.provider===e.model.provider&&t.model.id===e.model.id);return Vc({supported:n===void 0?t:r?.thinkingLevels??[],all:e.thinkingLevel===``||t.includes(e.thinkingLevel)?t:[e.thinkingLevel,...t],selected:e.thinkingLevel})}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return Uh(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[R(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=R(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await hs.cleanupPreview(e,t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${wF(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Ih(t.previewRequest)!==Ih(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=R(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await hs.cleanup(e,n);if(R(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){R(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${wF(e)}`})}}async runForceSessionCleanup(){let e=this.sessionCleanupDialog;if(!this.canCleanupSessions()){this.sessionCleanupDialog={...e??{},error:this.sessionCleanupUnavailableMessage(),runningForce:!1};return}let t=R(this.state);this.sessionCleanupDialog={...e??{},runningForce:!0,error:``};try{let e=await hs.forceCleanup(t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,forceCleanupResult:e,runningForce:!1,error:``},await this.sessions.applySessionCleanupResult(e,t)}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,runningForce:!1,error:`Failed to force cleanup: ${wF(e)}`})}}renderNavigationPanel(){return g`
|
|
7080
|
+
`}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-YP-JP);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let t=e===`navigation`?`workspace`:`navigation`;return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>`u`||!(`matchMedia`in window)||window.matchMedia(XP).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||E(e,w.sessionsDeleteArchived)}get projectStatisticsAvailable(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.projectUsageStatistics)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReload)}canReorderSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReorder)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return Hf(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.workspaceFileSuggestions)}sessionModelPolicySupported(e=R(this.state)){return sF(this.state,e)}starterModelPolicySelectionSupported(e=R(this.state)){return cF(this.state,e)}handleStarterModelPolicyCapabilityChange(e,t){let n=R(t);if(R(e)!==n||cF(e,n)||!cF(t,n)||!this.shouldShowSessionStartScreen(t))return;let r=t.selectedWorkspace;r!==void 0&&this.loadStarterSessionDefaults(r)}starterModelPolicyPreferenceScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),cwd:e.path}}starterModelPolicyPreferenceScopeMatchesCurrentSelection(e){let t=this.starterModelPolicyPreferenceScope();return t?.machineId===e.machineId&&t.cwd===e.cwd}handleStarterModelPolicyConfirmed(e){let t={machineId:e.machineId,cwd:e.session.cwd},n=this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(t);n&&this.state.selectedSession?.id===e.session.id&&this.state.selectedSession.cwd===e.session.cwd?(this.starterModelPolicy=Zs(e.policy),this.starterModelPolicyPreferenceReadError=``,this.confirmedStarterModelPolicyUiScope=t,this.confirmedStarterModelPolicyUiGeneration=this.starterModelPolicySelectionGeneration):n&&(this.confirmedStarterModelPolicyUiScope!==void 0||this.confirmedStarterModelPolicyUiGeneration!==void 0)&&(this.confirmedStarterModelPolicyUiScope=void 0,this.confirmedStarterModelPolicyUiGeneration=void 0,this.requestUpdate()),this.confirmedStarterModelPolicyPreferenceWriter.write(t,e.session)}starterNoticeScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),workspaceId:e.id}}publishStarterNotice(e){let t=this.starterNoticeScope();t?.machineId!==e.scope.machineId||t.workspaceId!==e.scope.workspaceId||(this.starterNotice=e)}syncStarterNotice(){let e=this.starterNotice;e!==void 0&&(Pc(e,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)||(this.starterNotice=void 0))}starterModelPolicyPreferenceSupported(e){let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.sessionsModelPolicyDefaults)}persistStarterModelPolicyPreference(e){let t=this.starterModelPolicyPreferenceScope(),n=rc(e);t===void 0||n===void 0||!this.starterModelPolicyPreferenceSupported(t.machineId)||this.starterModelPolicyPreferenceWriter.write(t,n)}loadModelTierCatalog(e){let t=this.state.selectedWorkspace?.id,n=++this.modelTierCatalogSeq,r=this.performModelTierCatalogLoad(e,t,n);this.modelTierCatalogLoad={machineId:e,workspaceId:t,promise:r};let i=()=>{this.modelTierCatalogLoad?.promise===r&&(this.modelTierCatalogLoad=void 0)};return r.then(i,i),r}async performModelTierCatalogLoad(e,t,n){let r=()=>n===this.modelTierCatalogSeq&&R(this.state)===e&&this.state.selectedWorkspace?.id===t;this.modelTierCatalogLoading=!0,this.modelTierCatalogError=``;try{let t=await es.settings(e);if(!r())return;this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.completeStarterModelPolicyFromActiveTier()}catch(e){if(!r())return;this.modelTierCatalogError=TF(e)}finally{n===this.modelTierCatalogSeq&&(this.modelTierCatalogLoading=!1)}}ensureModelTierCatalog(e){if(this.selectedMachineModelTierCatalog()!==void 0)return Promise.resolve();let t=this.state.selectedWorkspace?.id,n=this.modelTierCatalogLoad;return n?.machineId===e&&n.workspaceId===t?n.promise:this.loadModelTierCatalog(e)}resetStarterModelPolicyForScopeChange(){this.starterSessionDefaultsSeq+=1,this.starterModelPolicySelectionGeneration+=1,this.starterModelPolicy=void 0,this.starterModelPolicyPreferenceReadError=``,this.starterNotice=void 0,this.modelTierCatalogError=``}resetModelTierCatalogForMachineChange(){this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogMachineId=void 0,this.modelTierCatalog=void 0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``}handleModelTiersSaved(e,t){R(this.state)===e&&(this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.modelTierCatalogError=``,this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogLoading=!1,this.completeStarterModelPolicyFromActiveTier(),aF(this.state)!==void 0&&this.sessions.loadModelPolicy())}completeStarterModelPolicyFromActiveTier(){let e=this.starterSessionDefaults,t=this.starterModelPolicy,n=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0||n===void 0)return;let r=dc(t,e,n);uF(t,r)||(this.starterModelPolicy=r)}selectedMachineModelTierCatalog(){if(this.modelTierCatalogMachineId===R(this.state))return this.modelTierCatalog}preloadActiveModelPolicyInputs(){this.sessions.loadModelPolicy(),this.ensureModelTierCatalog(R(this.state))}async prepareActiveModelPolicyDraft(){if(!this.sessionModelPolicySupported())return;let e=rF(this.state);if(e===void 0||oF(this.state)===void 0)return;let t=this.activeModelPolicyDraftForState(this.state);if(t!==void 0)return t;let n=[];if(this.state.modelPolicy===void 0&&n.push(this.sessions.loadModelPolicy()),this.selectedMachineModelTierCatalog()===void 0&&n.push(this.ensureModelTierCatalog(R(this.state))),await Promise.all(n),rF(this.state)!==e)return;let r=this.activeModelPolicyDraftForState(this.state);if(r!==void 0)return r;let i=this.selectedMachineModelTierCatalog(),a=oF(this.state);if(i===void 0||a===void 0)return;let o=this.state.modelPolicy?.policy,s;if(o!==void 0)s=Qs({policy:o,catalog:i});else if(a.mode===`exact`)s=Qs({liveResolved:a.resolved,catalog:i});else{let e=Qs({catalog:i});s=a.tier===void 0?{...e,mode:`tiered`}:ac(e,a.tier)}return this.activeModelPolicyDraftScope=e,this.activeModelPolicyDraft=s,s}activeModelPolicyDraftForState(e){return this.activeModelPolicyDraftScope===rF(e)?this.activeModelPolicyDraft:void 0}setActiveModelPolicyDraft(e){let t=rF(this.state);t!==void 0&&(this.activeModelPolicyDraftScope=t,this.activeModelPolicyDraft=e)}resetActiveModelPolicyDraft(){this.cancelActiveModelPolicyApply(),this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0}cancelActiveModelPolicyApply(){this.activeModelPolicyApplyGeneration+=1,this.activeModelPolicyApplyTimer!==void 0&&window.clearTimeout(this.activeModelPolicyApplyTimer),this.activeModelPolicyApplyTimer=void 0}scheduleActiveExactModelPolicyApply(){this.cancelActiveModelPolicyApply();let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e?.mode!==`exact`||!uc(e,t))return;let n=this.activeModelPolicyApplyGeneration;this.activeModelPolicyApplyTimer=window.setTimeout(()=>{n===this.activeModelPolicyApplyGeneration&&(this.activeModelPolicyApplyTimer=void 0,this.applyActiveModelPolicyDraft())},ZP)}async applyActiveModelPolicyDraft(){let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e===void 0||!uc(e,t)||t===void 0)return;let n=lc(e,t);if(n===void 0)return;let r=this.activeModelPolicyDraftScope,i=this.state.modelPolicy;if(await this.sessions.saveModelPolicy(n),r!==rF(this.state)||this.activeModelPolicyDraft!==e)return;if(this.state.modelPolicyError!==void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}if(this.state.modelPolicy===i)return;let a=this.state.modelPolicy?.policy;if(a===void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}this.setActiveModelPolicyDraft(Qs({policy:a,catalog:t}))}policyThinkingOptions(e,t){let n=this.selectedMachineModelTierCatalog(),r=n?.models.find(t=>t.model.provider===e.model.provider&&t.model.id===e.model.id);return Vc({supported:n===void 0?t:r?.thinkingLevels??[],all:e.thinkingLevel===``||t.includes(e.thinkingLevel)?t:[e.thinkingLevel,...t],selected:e.thinkingLevel})}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return Uh(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[R(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=R(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await hs.cleanupPreview(e,t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${TF(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Ih(t.previewRequest)!==Ih(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=R(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await hs.cleanup(e,n);if(R(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){R(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${TF(e)}`})}}async runForceSessionCleanup(){let e=this.sessionCleanupDialog;if(!this.canCleanupSessions()){this.sessionCleanupDialog={...e??{},error:this.sessionCleanupUnavailableMessage(),runningForce:!1};return}let t=R(this.state);this.sessionCleanupDialog={...e??{},runningForce:!0,error:``};try{let e=await hs.forceCleanup(t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,forceCleanupResult:e,runningForce:!1,error:``},await this.sessions.applySessionCleanupResult(e,t)}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,runningForce:!1,error:`Failed to force cleanup: ${TF(e)}`})}}renderNavigationPanel(){return g`
|
|
7079
7081
|
<app-navigation-panel
|
|
7080
7082
|
.machines=${this.state.machines}
|
|
7081
7083
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -7158,14 +7160,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7158
7160
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
7159
7161
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
7160
7162
|
></app-navigation-panel>
|
|
7161
|
-
`}canOpenSessionHistory(){let e=this.state.selectedSession;return e!==void 0&&e.persisted!==!1&&e.path!==``}openSessionHistory(){let e=this.state.selectedSession;e===void 0||!this.canOpenSessionHistory()||(this.historyWindow={machineId:R(this.state),session:e})}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}cancelPendingNavigationSelection(){this.navigationSelectionSeq+=1}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async selectSessionFromNavigation(e){if(this.state.selectedWorkspace?.path===e.cwd){await this.sessions.selectSession(e);return}let t=this.state.workspaces.find(t=>t.path===e.cwd);if(t===void 0){this.setState({error:`The session's workspace is no longer available.`});return}await this.workspaces.selectWorkspace(t,{sessionId:e.id})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state),r=this.starterModelPolicySelectionGeneration,i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer();if(i&&a===void 0&&(this.starterModelPolicy===void 0||this.selectedMachineModelTierCatalog()===void 0)){if(await this.loadMissingStarterPlusModelPolicyInputs(t,n,r),!e()||this.starterModelPolicySelectionGeneration!==r)return;i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer()}if(this.starterModelPolicyInputs()?.status.blockedReason!==void 0){let t=this.starterNoticeScope();e()&&t!==void 0&&this.publishStarterNotice(jc(t));return}if(i&&a===void 0)return;this.starterNotice=void 0;let o=t.id,s=this.starterModelPolicy;(a===void 0?this.sessions.startSession(this.starterModelPolicyStartSnapshot()):this.sessions.startPlusSession(a)).then(e=>{i||this.clearStarterModelPolicyAfterSuccessfulStart(e,o,s)}).catch(t=>{if(e()){let e={machineId:n,workspaceId:o};this.publishStarterNotice(Mc(`start-failed`,`Could not start the session. ${
|
|
7163
|
+
`}canOpenSessionHistory(){let e=this.state.selectedSession;return e!==void 0&&e.persisted!==!1&&e.path!==``}openSessionHistory(){let e=this.state.selectedSession;e===void 0||!this.canOpenSessionHistory()||(this.historyWindow={machineId:R(this.state),session:e})}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}cancelPendingNavigationSelection(){this.navigationSelectionSeq+=1}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async selectSessionFromNavigation(e){if(this.state.selectedWorkspace?.path===e.cwd){await this.sessions.selectSession(e);return}let t=this.state.workspaces.find(t=>t.path===e.cwd);if(t===void 0){this.setState({error:`The session's workspace is no longer available.`});return}await this.workspaces.selectWorkspace(t,{sessionId:e.id})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state),r=this.starterModelPolicySelectionGeneration,i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer();if(i&&a===void 0&&(this.starterModelPolicy===void 0||this.selectedMachineModelTierCatalog()===void 0)){if(await this.loadMissingStarterPlusModelPolicyInputs(t,n,r),!e()||this.starterModelPolicySelectionGeneration!==r)return;i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer()}if(this.starterModelPolicyInputs()?.status.blockedReason!==void 0){let t=this.starterNoticeScope();e()&&t!==void 0&&this.publishStarterNotice(jc(t));return}if(i&&a===void 0)return;this.starterNotice=void 0;let o=t.id,s=this.starterModelPolicy;(a===void 0?this.sessions.startSession(this.starterModelPolicyStartSnapshot()):this.sessions.startPlusSession(a)).then(e=>{i||this.clearStarterModelPolicyAfterSuccessfulStart(e,o,s)}).catch(t=>{if(e()){let e={machineId:n,workspaceId:o};this.publishStarterNotice(Mc(`start-failed`,`Could not start the session. ${TF(t)}`,e))}}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e===`chat`){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e===`machines`&&!eP(this.state.machines)){await this.focusNavigationSection(`projects`);return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView(`navigation`),this.navigationSections.expand(e),await this.updateComplete,await OF(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await OF(),this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=R(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
|
|
7162
7164
|
<session-tree-navigator
|
|
7163
7165
|
.tree=${e.treeDialog}
|
|
7164
7166
|
.onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
|
|
7165
7167
|
.onAbort=${()=>this.sessions.abortTreeNavigation()}
|
|
7166
7168
|
.onCancel=${()=>{this.closeSessionTreeNavigator()}}
|
|
7167
7169
|
></session-tree-navigator>
|
|
7168
|
-
`}workspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}synchronizeMemoryPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.memory.updatePolling(!1);return}this.synchronizeMemoryPolling(e)}synchronizeMemoryPolling(e){let t=e.some(e=>
|
|
7170
|
+
`}workspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}synchronizeMemoryPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.memory.updatePolling(!1);return}this.synchronizeMemoryPolling(e)}synchronizeMemoryPolling(e){let t=e.some(e=>dF(e)&&ug(e,this.createActivityRailContext(e.id),this.reportActivityRailError));this.memory.updatePolling(t)}synchronizeLearnedSkillsPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.learnedSkills.updatePolling(!1);return}this.synchronizeLearnedSkillsPolling(e)}synchronizeLearnedSkillsPolling(e){let t=e.some(e=>fF(e)&&ug(e,this.createActivityRailContext(e.id),this.reportActivityRailError));this.learnedSkills.updatePolling(t)}visibleWorkspacePanels(){let e=this.hiddenWorkspacePanelTools();return this.workspacePanels().filter(t=>!e.includes(t.id))}hiddenWorkspacePanelTools(){let e=[];return this.terminalTabHidden&&e.push(`core:workspace.terminal`),this.infoTabHidden&&e.push(`core:workspace.info`),e}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:`Loading projects…`,body:`Looking for projects you have added to PI WEBUI.`}:e===void 0?this.state.projects.length===0?{title:`No projects yet`,body:`Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace.`}:{title:`Select a project`,body:`Choose a project from the sidebar, then select a workspace to inspect files, Git, or terminals.`}:this.state.isLoadingWorkspaces?{title:`Loading workspaces…`,body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:`No workspaces found`,body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:`Select a workspace`,body:`Choose a workspace in ${e.name} to inspect files, Git, or terminals.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?`Loading projects…`:this.state.isLoadingSessions?`Loading sessions…`:this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?`Add a project to start a session.`:`Select a project and workspace to start a session.`:`Select a workspace to start a session.`:`Select or start a session.`}shouldShowSessionStartScreen(e){return e.selectedWorkspace!==void 0&&e.selectedSession===void 0&&!e.isLoadingSessions&&e.sessions.every(e=>e.archived===!0)&&e.error===``}renderStarterNotice(){let e=Nc(this.starterNotice,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)??this.confirmedStarterModelPolicyWarning();return e===void 0?null:g`<p class="starter-notice" role="alert">${e}</p>`}renderSessionStartScreen(e){let t=e.selectedWorkspace;if(t===void 0)return g``;let n=this.starterSessionDefaults,r=this.starterSessionConfiguration(),i=this.selectedMachineModelTierCatalog(),a=n!==void 0&&(this.starterModelPolicySelectionSupported()?(i?.models.length??0)>0:n.models.length>0),o=n!==void 0&&n.thinkingLevels.length>0,s=this.starterModelPolicyInputs(),c=s===void 0||n===void 0?[]:this.policyThinkingOptions(this.starterModelPolicy?.exact??s.status.resolved,n.thinkingLevels);return g`
|
|
7169
7171
|
<section class="session-start-screen" aria-labelledby="session-start-heading">
|
|
7170
7172
|
<div class="session-start-content">
|
|
7171
7173
|
<p class="session-start-eyebrow">PI WEBUI · ${t.label}</p>
|
|
@@ -7177,7 +7179,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7177
7179
|
<p class="session-start-hint">Describe a goal, paste a task, or attach a file to begin.</p>
|
|
7178
7180
|
</div>
|
|
7179
7181
|
</section>
|
|
7180
|
-
`}starterSessionConfiguration(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;return e===void 0||t===void 0||!this.starterModelPolicySelectionSupported()?e:{...e,model:{provider:t.exact.model.provider,id:t.exact.model.id},thinkingLevel:t.exact.thinkingLevel}}starterModelPolicyInputs(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.selectedMachineModelTierCatalog();if(this.starterModelPolicySelectionSupported()){let r=n===void 0?{kind:`blocked`,reason:this.modelTierCatalogError===``?`Loading model policy choices`:this.modelTierCatalogError}:fc(t,n),i={mode:t.mode,...t.tier===void 0?{}:{tier:t.tier},resolved:r.kind===`ready`?r.resolved:t.exact,ladderValid:n?.valid??!0,...r.kind===`blocked`?{blockedReason:r.reason}:{}};return{status:i,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:i}}}}let r=t.tier,i=r===void 0?void 0:n?.rows[r],a=t.mode===`tiered`&&r!==void 0&&i?.valid===!0?n?.ladder?.[r]:void 0,o=ec(e),s=t.mode===`exact`&&o!==void 0&&!ic(t.exact,o),c=t.mode===`tiered`&&a===void 0,l={mode:t.mode,...r===void 0?{}:{tier:r},resolved:a??t.exact,ladderValid:n===void 0||n.valid,...c?{blockedReason:n?.configError??(this.modelTierCatalogError===``?`Choose a valid model tier before starting`:this.modelTierCatalogError)}:s?{blockedReason:`Choose a model and thinking level before starting`}:{}};return{status:l,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:l}}}}starterModelPolicyBlocksStart(){return this.starterModelPolicyInputs()?.status.blockedReason!==void 0}starterModelPolicyError(){if(this.modelTierCatalogError!==``)return this.modelTierCatalogError;if(this.starterModelPolicySelectionSupported()){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?this.starterModelPolicyPreferenceReadError:`${ZP} ${e}`}let e=this.starterModelPolicyPreferenceScope(),t=e===void 0?void 0:this.starterModelPolicyPreferenceWriter.snapshot(e).error;return t===void 0?this.starterModelPolicyPreferenceReadError:`Could not remember this model policy; this session will still use it. ${t}`}currentConfirmedStarterModelPolicyWriterSnapshot(){let e=this.confirmedStarterModelPolicyUiScope;if(!(e===void 0||this.confirmedStarterModelPolicyUiGeneration!==this.starterModelPolicySelectionGeneration||!this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)))return this.confirmedStarterModelPolicyPreferenceWriter.snapshot(e)}confirmedStarterModelPolicyWarning(){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?void 0:`${ZP} ${e}`}starterModelPolicyStartSnapshot(){let e=this.starterModelPolicy,t=this.starterSessionDefaults;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;if(e.mode===`tiered`)return e.tier===void 0?void 0:{mode:`tiered`,tier:e.tier};let n=ec(t);if(!(n===void 0||ic(n,e.exact)))return{mode:`exact`,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel}}}starterPlusModelPolicyInitializer(){if(!this.starterModelPolicySelectionSupported())return;let e=this.starterModelPolicy,t=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0)return;let n=fc(e,t);return n.kind===`ready`?n.initialModelPolicy:void 0}async loadMissingStarterPlusModelPolicyInputs(e,t,n){if(this.starterModelPolicy===void 0){await this.loadStarterSessionDefaults(e,{awaitModelTierCatalog:!0,expectedSelectionGeneration:n});return}this.selectedMachineModelTierCatalog()===void 0&&await this.ensureModelTierCatalog(t)}clearStarterModelPolicyAfterSuccessfulStart(e,t,n){!e||this.state.selectedWorkspace?.id!==t||this.starterModelPolicy!==n||(this.starterModelPolicy=void 0)}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case`core:workspace.files`:return`files`;case`core:workspace.git`:return`git`;case`core:workspace.terminal`:return`terminal`;default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=$P(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:n=>ms.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await ms.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await ms.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await ms.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelTerminal(e,t,n){let r=this.terminalCommandRunsForOrigin(n,t);return{open:n=>{this.openRuntimeTerminal(t,e,n)},runCommand:t=>r.runCommand({...t,workspace:e})}}createWorkspacePanelContext(e){let t=$P(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Tv({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:this.createWorkspacePanelTerminal(e,n,i),openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUiUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Ms(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onRefreshMemory:()=>{this.memory.refresh()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return Ny(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,closesActionPalette:!0,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.toggle-terminal-tab`,title:this.terminalTabHidden?`Show Terminal Tab`:`Hide Terminal Tab`,description:this.terminalTabHidden?`Show the terminal tab in the workspace panel`:`Hide the terminal tab from the workspace panel`,group:`View`,run:()=>{this.toggleTerminalTab()}},{id:`app.layout.toggle-info-tab`,title:this.infoTabHidden?`Show Info Tab`:`Hide Info Tab`,description:this.infoTabHidden?`Show the info tab in the workspace panel`:`Hide the info tab from the workspace panel`,group:`View`,run:()=>{this.toggleInfoTab()}},{id:`app.layout.reset-navigation-panel-size`,title:`Reset Navigation Panel Size`,description:`Restore the navigation panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`Reset Workspace Panel Size`,description:`Restore the workspace panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`Reset Panel Sizes`,description:`Restore all side panels to their default widths`,group:`View`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`Focus Machines`,description:`Move keyboard focus to the machine selector`,shortcut:`mod+g m`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`Focus Projects`,description:`Move keyboard focus to the projects list`,shortcut:`mod+g p`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`Focus Workspaces`,description:`Move keyboard focus to the workspaces list`,shortcut:`mod+g w`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`Focus Sessions`,description:`Move keyboard focus to the sessions list`,shortcut:`mod+g s`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins(`PI WEBUI plugins`,()=>ov())}async loadPluginsForSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!==`remote`||this.loadedMachinePluginIds.has(e.id))return;let t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;let n=this.registerExternalPlugins(`PI WEBUI plugins from ${e.name}`,()=>ov(`api/machines/${encodeURIComponent(e.id)}/pi-webui-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.plugins.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,n),await n}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEBUI plugin ${t.id}`,e)}return this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){return this.createPluginRuntimeContextForOrigin(`core`,R(this.state))}createPluginRuntimeContextForOrigin(e,t){let n=e=>wv({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(e,t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.openProjectDialog()},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),checkForPiWebUiUpdates:()=>this.piWebUiStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},n);return n(e)}createActivityRailContext(e){let t=$P(this.state),n=this.state.selectedWorkspace,r=this.activeActivityRailId===e?this.activeActivityRailGeneration:void 0,i=a=>Ev({...this.createPluginRuntimeContextForOrigin(a,t.id),machine:t,...n===void 0?{}:{workspaceScope:{workspace:n,files:this.createWorkspaceFiles(n,t.id),terminal:this.createWorkspacePanelTerminal(n,t.id,a)}},host:{requestRender:()=>{this.requestUpdate()},close:()=>{r!==void 0&&this.closeActivityRailItem(e,r)}},onRefreshMemory:()=>{this.memory.refresh()},onRefreshLearnedSkills:()=>{this.learnedSkills.refresh()}},i);return i(`core`)}activityRailItems(){let e=this.plugins.getActivityRailItems();return this.synchronizeMemoryPollingForSelectedWorkspace(e),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(e),e.flatMap(e=>this.projectActivityRailItems([e],this.createActivityRailContext(e.id)))}projectActivityRailItems(e,t){return dg(e,t,this.reportActivityRailError)}activeActivityRailItem(){let e=this.activeActivityRailId;if(e===void 0)return;let t=this.resolveActivityRailItem(e);return t===void 0?void 0:{...t,generation:this.activeActivityRailGeneration}}openActivityRailItem(e,t){this.resolveActivityRailItem(e)!==void 0&&(this.closeCompactActivityRail(),this.activityRailRestoreFocus=t,this.activeActivityRailGeneration+=1,this.activeActivityRailId=e)}resolveActivityRailItem(e){let t=this.plugins.getActivityRailItems().find(t=>t.id===e);if(t===void 0)return;let n=this.createActivityRailContext(e);if(this.projectActivityRailItems([t],n).some(t=>t.id===e))return{activity:t,context:n}}closeActivityRailItem(e,t){if(this.activeActivityRailId!==e||this.activeActivityRailGeneration!==t)return;let n=this.activityRailRestoreFocus;this.activityRailRestoreFocus=void 0,this.activeActivityRailId=void 0,n!==void 0&&this.updateComplete.then(()=>{this.activeActivityRailId===void 0&&n()})}restoreActivityRailFocus(e){if(e.isConnected){e.focus();return}let t=this.compactActivityRailLauncher;if(t?.isConnected===!0){t.focus();return}this.currentCompactActivityRailLauncher()?.focus()}currentCompactActivityRailLauncher(){let e=this.renderRoot.querySelector(`app-context-bar`)?.shadowRoot?.querySelector(`.activity-rail-action-button`);return e?.isConnected===!0?e:void 0}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Cm(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(Pg(this.state,e))return;let t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?\n\nThis will run git worktree remove and delete:\n${e.path}\n\nThe Git branch will not be deleted.`))return;let n=R(this.state);try{let t=await ms.deleteWorkspace(e.projectId,e.id,n);if(R(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(R(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){R(this.state)===n&&this.setState({error:`Failed to start workspace deletion: ${wF(e)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(R(this.state)!==t)return;let n=Fg(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=R(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{let n=await this.terminalCommandRunsForOrigin(`core`,e).listCommandRuns(jg(t.id));if(R(this.state)!==e)return;let r=Mg(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Ig(t)||await this.handleCompletedWorkspaceDeletionRun(t,e)}catch(e){console.warn(`Failed to refresh workspace deletion runs`,e)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){let e=Object.values(this.state.workspaceDeletionRuns).some(Ig);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=R(this.state)){if(R(this.state)!==t)return;let n=SF(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Fg(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),R(this.state)!==t)return;this.setState({workspaceDeletionRuns:EF(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace deletion failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}openProjectBrowser(e){this.projectBrowserRestoreFocus=e,this.projectBrowserOpen=!0}async showProjectStatistics(e){let t=++this.statisticsRequestGeneration,n=R(this.state),r=()=>t===this.statisticsRequestGeneration&&R(this.state)===n;this.statisticsProject=e,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!0;try{let t=await ms.workspaces(e.id,n);if(!r())return;let i={projectPath:e.path,liveCwds:t.map(e=>e.path)};ps.projectUsageCount(i,n).then(({sessionCount:e})=>{r()&&this.statisticsLoading&&(this.statisticsSessionCount=e)},()=>void 0);let a=await ps.projectUsage(i,n);if(!r())return;this.statisticsReport=a}catch(e){if(!r())return;this.statisticsError=e instanceof Error?e.message:String(e)}finally{r()&&(this.statisticsLoading=!1)}}closeProjectStatistics(){this.statisticsRequestGeneration+=1,this.statisticsProject=void 0,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!1}closeProjectBrowser(e={}){let t=e.restoreFocus===!0?this.projectBrowserRestoreFocus:void 0;this.projectBrowserRestoreFocus=void 0,this.projectBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectProjectFromBrowser(e){this.closeProjectBrowser(),this.selectNavigationItem(`projects`,`workspaces`,()=>this.workspaces.selectProject(e))}addProjectFromBrowser(){this.closeProjectBrowser(),this.openProjectDialog()}openSessionBrowser(e){this.state.selectedProject!==void 0&&(this.sessionBrowserRestoreFocus=e,this.sessionBrowserOpen=!0)}closeSessionBrowser(e={}){let t=e.restoreFocus===!0?this.sessionBrowserRestoreFocus:void 0;this.sessionBrowserRestoreFocus=void 0,this.sessionBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectSessionFromBrowser(e){this.closeSessionBrowser(),this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e))}openProjectDialog(){this.setState({projectDialogOpen:!0})}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebUiStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEBUI gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let e=this.state.selectedMachine;e?.kind!==`remote`||e.baseUrl===void 0||window.open(e.baseUrl,`_blank`,`noopener,noreferrer`)}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id,r=[...e].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);if(!this.sessionModelPolicySupported()){await this.sessions.setModel(n,r);return}let i=await this.prepareActiveModelPolicyDraft();if(i===void 0||i!==this.activeModelPolicyDraftForState(this.state)||i.mode!==`exact`)return;let a=this.selectedMachineModelTierCatalog(),o=a?.models.find(e=>e.model.provider===n&&e.model.id===r);if(o===void 0){a!==void 0&&(this.modelTierCatalogError=`Model ${n}/${r} is unavailable in the model policy catalog`);return}this.modelTierCatalogError=``,this.setActiveModelPolicyDraft(sc(i,o)),this.scheduleActiveExactModelPolicyApply()}openStarterModelDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported(),n=t?this.starterModelPolicy?.exact:void 0,r=n?.model.provider??e.model?.provider,i=n?.model.id??e.model?.id,a=t?(this.selectedMachineModelTierCatalog()?.models??[]).map(e=>({provider:e.model.provider,id:e.model.id,...e.name===void 0?{}:{name:e.name}})):[...e.models],o=r!==void 0&&i!==void 0&&!a.some(e=>e.provider===r&&e.id===i),s=[...o?[...a,{provider:r,id:i}]:a].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Default Model`,source:`starter`,...r!==void 0&&i!==void 0?{selectedValue:`${r}/${i}`}:{},options:s.map(e=>{let t=e.provider??``,n=e.id??``,a=t===r&&n===i;return{value:`${t}/${n}`,label:n+(a?` ✓ current`:``)+(a&&o?` (unavailable)`:``),...t===``?{}:{group:t}}})}})}async pickStarterModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(!(t<=0)){if(this.starterModelPolicySelectionSupported()){let n=this.starterModelPolicy,r=e.slice(0,t),i=e.slice(t+1),a=this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===r&&e.model.id===i);if(n===void 0||a===void 0)return;this.setStarterModelPolicyDraft(sc(n,a));return}await this.updateStarterSessionDefaults({model:{provider:e.slice(0,t),modelId:e.slice(t+1)}})}}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?IP:FP;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${LP}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${LP}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===FP||e===IP){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===FP},this.applyPreferredTheme(!0);return}if(!e.startsWith(LP))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,bg(t),e&&yg(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return xg({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Cg(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?`Follow the system light/dark preference when the selected theme has a pair.`:e.selectedThemePair===void 0?`On, but the selected theme has no light/dark pair, so it will stay selected.`:`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?`light`:`dark`} preference.`}themeOptionLabel(e,t){let n=[...e.id===t?[`selected`]:[],...e.id===this.activeThemeId&&e.id!==t?[`active`]:[]];return n.length===0?e.name:`${e.name} ✓ ${n.join(` · `)}`}themeOptionDescription(e){let t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push(`auto pair`),e.description!==void 0&&t.push(e.description),t.join(` · `)}async openThinkingDialog(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=OF(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){if(this.setState({thinkingDialog:void 0}),e===``)return;if(!this.sessionModelPolicySupported()){await this.sessions.setThinkingLevel(e);return}let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode!==`exact`)return;let n=cc(t,e);if(this.setActiveModelPolicyDraft(n),(this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===n.exact.model.provider&&e.model.id===n.exact.model.id))?.thinkingLevels.includes(e)!==!0){this.cancelActiveModelPolicyApply(),this.modelTierCatalogError=`Thinking level ${e} is unsupported by ${n.exact.model.provider}/${n.exact.model.id}`;return}this.modelTierCatalogError=``,this.scheduleActiveExactModelPolicyApply()}openStarterThinkingDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported()?this.starterModelPolicy?.exact.thinkingLevel??e.thinkingLevel:e.thinkingLevel,n=e.thinkingLevels.includes(t)?e.thinkingLevels:[t,...e.thinkingLevels];this.setState({thinkingDialog:{title:`Select Default Thinking Level`,source:`starter`,selectedValue:t,options:n.map(e=>{let n=OF(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickStarterThinking(e){if(this.setState({thinkingDialog:void 0}),e!==``){if(this.starterModelPolicySelectionSupported()){let t=this.starterModelPolicy;t!==void 0&&this.setStarterModelPolicyDraft(cc(t,e));return}await this.updateStarterSessionDefaults({thinkingLevel:e})}}async updateStarterSessionDefaults(e){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state);try{let r=await hs.updateSessionDefaults(t.path,e,n);if(R(this.state)!==n||this.state.selectedWorkspace?.id!==t.id)return;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let i=this.starterModelPolicy,a=i===void 0?tc(r):nc(i,r);this.starterModelPolicy=a;let o=ec(r);a.mode===`exact`&&o!==void 0&&ic(a.exact,o)&&this.persistStarterModelPolicyPreference(a)}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.publishStarterNotice(Mc(`defaults-failed`,`Could not save this workspace's model defaults. ${wF(e)}`,{machineId:n,workspaceId:t.id}))}}sendPrompt(e,t,n,r){!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,n,r)}async ensureStarterModelPolicyCatalog(){let e=this.selectedMachineModelTierCatalog();return e===void 0?(await this.ensureModelTierCatalog(R(this.state)),this.selectedMachineModelTierCatalog()):e}setStarterModelPolicyDraft(e){this.starterNotice=void 0;let t={mode:e.mode,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel},...e.tier===void 0?{}:{tier:e.tier}};return this.starterModelPolicy=t,t}applyGitUpdateManagerStatus(e,t,n){let r=this.state.selectedWorkspace;R(this.state)!==t||r?.id!==e.id||r.projectId!==e.projectId||this.setState({gitStatus:n,gitStale:!1})}startTerminalModalPointerInteraction(e,t){if(this.terminalModalMaximized||t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.terminal-modal-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=Ky(this.terminalModalBoundsFromFrame(r),this.terminalModalViewport());n.setPointerCapture(t.pointerId),this.terminalModalBounds=i,this.terminalModalPointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}terminalModalBoundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}terminalModalViewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}terminalModalFrameStyle(){let e=this.terminalModalMaximized?void 0:this.terminalModalBounds,t=e===void 0?``:`; left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px`;return`--terminal-modal-opacity: ${String(this.terminalModalOpacity)}%${t};`}finishTerminalModalPointerInteraction(){let e=this.terminalModalPointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.terminalModalPointerInteraction=void 0}}persistTerminalModalPreferences(){eb({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,this.persistWorkspaceTabVisibility()}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,this.persistWorkspaceTabVisibility()}persistWorkspaceTabVisibility(){cb({terminalHidden:this.terminalTabHidden,infoHidden:this.infoTabHidden})}activeModelPolicyInputs(e){let t=e.status?.modelPolicy;if(e.status===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.activeModelPolicyDraftForState(e);if(n===void 0)return{error:e.modelPolicyError??this.modelTierCatalogError,status:t,editorStatus:e.status,thinkingOptions:this.policyThinkingOptions(t.resolved,e.availableThinkingLevels)};let r=n.tier,i=r===void 0||this.selectedMachineModelTierCatalog()?.rows[r].valid!==!0?void 0:this.selectedMachineModelTierCatalog()?.ladder?.[r],a=n.mode===`exact`?n.exact:i??t.resolved,o={mode:n.mode,...r===void 0?{}:{tier:r},resolved:{model:{...a.model},thinkingLevel:a.thinkingLevel},ladderValid:t.ladderValid,...t.blockedReason===void 0?{}:{blockedReason:t.blockedReason}},s=n.exact.model.provider!==``&&n.exact.model.id!==``,c=n.mode===`exact`?{...e.status,...s?{model:{...n.exact.model}}:{},thinkingLevel:n.exact.thinkingLevel,modelPolicy:o}:{...e.status,modelPolicy:o};return{error:e.modelPolicyError??this.modelTierCatalogError,status:o,editorStatus:c,thinkingOptions:this.policyThinkingOptions(n.exact,e.availableThinkingLevels)}}renderChatView(e,t){return g`
|
|
7182
|
+
`}starterSessionConfiguration(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;return e===void 0||t===void 0||!this.starterModelPolicySelectionSupported()?e:{...e,model:{provider:t.exact.model.provider,id:t.exact.model.id},thinkingLevel:t.exact.thinkingLevel}}starterModelPolicyInputs(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.selectedMachineModelTierCatalog();if(this.starterModelPolicySelectionSupported()){let r=n===void 0?{kind:`blocked`,reason:this.modelTierCatalogError===``?`Loading model policy choices`:this.modelTierCatalogError}:fc(t,n),i={mode:t.mode,...t.tier===void 0?{}:{tier:t.tier},resolved:r.kind===`ready`?r.resolved:t.exact,ladderValid:n?.valid??!0,...r.kind===`blocked`?{blockedReason:r.reason}:{}};return{status:i,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:i}}}}let r=t.tier,i=r===void 0?void 0:n?.rows[r],a=t.mode===`tiered`&&r!==void 0&&i?.valid===!0?n?.ladder?.[r]:void 0,o=ec(e),s=t.mode===`exact`&&o!==void 0&&!ic(t.exact,o),c=t.mode===`tiered`&&a===void 0,l={mode:t.mode,...r===void 0?{}:{tier:r},resolved:a??t.exact,ladderValid:n===void 0||n.valid,...c?{blockedReason:n?.configError??(this.modelTierCatalogError===``?`Choose a valid model tier before starting`:this.modelTierCatalogError)}:s?{blockedReason:`Choose a model and thinking level before starting`}:{}};return{status:l,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:l}}}}starterModelPolicyBlocksStart(){return this.starterModelPolicyInputs()?.status.blockedReason!==void 0}starterModelPolicyError(){if(this.modelTierCatalogError!==``)return this.modelTierCatalogError;if(this.starterModelPolicySelectionSupported()){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?this.starterModelPolicyPreferenceReadError:`${QP} ${e}`}let e=this.starterModelPolicyPreferenceScope(),t=e===void 0?void 0:this.starterModelPolicyPreferenceWriter.snapshot(e).error;return t===void 0?this.starterModelPolicyPreferenceReadError:`Could not remember this model policy; this session will still use it. ${t}`}currentConfirmedStarterModelPolicyWriterSnapshot(){let e=this.confirmedStarterModelPolicyUiScope;if(!(e===void 0||this.confirmedStarterModelPolicyUiGeneration!==this.starterModelPolicySelectionGeneration||!this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)))return this.confirmedStarterModelPolicyPreferenceWriter.snapshot(e)}confirmedStarterModelPolicyWarning(){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?void 0:`${QP} ${e}`}starterModelPolicyStartSnapshot(){let e=this.starterModelPolicy,t=this.starterSessionDefaults;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;if(e.mode===`tiered`)return e.tier===void 0?void 0:{mode:`tiered`,tier:e.tier};let n=ec(t);if(!(n===void 0||ic(n,e.exact)))return{mode:`exact`,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel}}}starterPlusModelPolicyInitializer(){if(!this.starterModelPolicySelectionSupported())return;let e=this.starterModelPolicy,t=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0)return;let n=fc(e,t);return n.kind===`ready`?n.initialModelPolicy:void 0}async loadMissingStarterPlusModelPolicyInputs(e,t,n){if(this.starterModelPolicy===void 0){await this.loadStarterSessionDefaults(e,{awaitModelTierCatalog:!0,expectedSelectionGeneration:n});return}this.selectedMachineModelTierCatalog()===void 0&&await this.ensureModelTierCatalog(t)}clearStarterModelPolicyAfterSuccessfulStart(e,t,n){!e||this.state.selectedWorkspace?.id!==t||this.starterModelPolicy!==n||(this.starterModelPolicy=void 0)}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case`core:workspace.files`:return`files`;case`core:workspace.git`:return`git`;case`core:workspace.terminal`:return`terminal`;default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=eF(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:n=>ms.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await ms.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await ms.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await ms.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelTerminal(e,t,n){let r=this.terminalCommandRunsForOrigin(n,t);return{open:n=>{this.openRuntimeTerminal(t,e,n)},runCommand:t=>r.runCommand({...t,workspace:e})}}createWorkspacePanelContext(e){let t=eF(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Tv({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:this.createWorkspacePanelTerminal(e,n,i),openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUiUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Ms(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onRefreshMemory:()=>{this.memory.refresh()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return Ny(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,closesActionPalette:!0,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.toggle-terminal-tab`,title:this.terminalTabHidden?`Show Terminal Tab`:`Hide Terminal Tab`,description:this.terminalTabHidden?`Show the terminal tab in the workspace panel`:`Hide the terminal tab from the workspace panel`,group:`View`,run:()=>{this.toggleTerminalTab()}},{id:`app.layout.toggle-info-tab`,title:this.infoTabHidden?`Show Info Tab`:`Hide Info Tab`,description:this.infoTabHidden?`Show the info tab in the workspace panel`:`Hide the info tab from the workspace panel`,group:`View`,run:()=>{this.toggleInfoTab()}},{id:`app.layout.reset-navigation-panel-size`,title:`Reset Navigation Panel Size`,description:`Restore the navigation panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`Reset Workspace Panel Size`,description:`Restore the workspace panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`Reset Panel Sizes`,description:`Restore all side panels to their default widths`,group:`View`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`Focus Machines`,description:`Move keyboard focus to the machine selector`,shortcut:`mod+g m`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`Focus Projects`,description:`Move keyboard focus to the projects list`,shortcut:`mod+g p`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`Focus Workspaces`,description:`Move keyboard focus to the workspaces list`,shortcut:`mod+g w`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`Focus Sessions`,description:`Move keyboard focus to the sessions list`,shortcut:`mod+g s`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins(`PI WEBUI plugins`,()=>ov())}async loadPluginsForSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!==`remote`||this.loadedMachinePluginIds.has(e.id))return;let t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;let n=this.registerExternalPlugins(`PI WEBUI plugins from ${e.name}`,()=>ov(`api/machines/${encodeURIComponent(e.id)}/pi-webui-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.plugins.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,n),await n}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEBUI plugin ${t.id}`,e)}return this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){return this.createPluginRuntimeContextForOrigin(`core`,R(this.state))}createPluginRuntimeContextForOrigin(e,t){let n=e=>wv({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(e,t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.openProjectDialog()},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),checkForPiWebUiUpdates:()=>this.piWebUiStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},n);return n(e)}createActivityRailContext(e){let t=eF(this.state),n=this.state.selectedWorkspace,r=this.activeActivityRailId===e?this.activeActivityRailGeneration:void 0,i=a=>Ev({...this.createPluginRuntimeContextForOrigin(a,t.id),machine:t,...n===void 0?{}:{workspaceScope:{workspace:n,files:this.createWorkspaceFiles(n,t.id),terminal:this.createWorkspacePanelTerminal(n,t.id,a)}},host:{requestRender:()=>{this.requestUpdate()},close:()=>{r!==void 0&&this.closeActivityRailItem(e,r)}},onRefreshMemory:()=>{this.memory.refresh()},onRefreshLearnedSkills:()=>{this.learnedSkills.refresh()}},i);return i(`core`)}activityRailItems(){let e=this.plugins.getActivityRailItems();return this.synchronizeMemoryPollingForSelectedWorkspace(e),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(e),e.flatMap(e=>this.projectActivityRailItems([e],this.createActivityRailContext(e.id)))}projectActivityRailItems(e,t){return dg(e,t,this.reportActivityRailError)}activeActivityRailItem(){let e=this.activeActivityRailId;if(e===void 0)return;let t=this.resolveActivityRailItem(e);return t===void 0?void 0:{...t,generation:this.activeActivityRailGeneration}}openActivityRailItem(e,t){this.resolveActivityRailItem(e)!==void 0&&(this.closeCompactActivityRail(),this.activityRailRestoreFocus=t,this.activeActivityRailGeneration+=1,this.activeActivityRailId=e)}resolveActivityRailItem(e){let t=this.plugins.getActivityRailItems().find(t=>t.id===e);if(t===void 0)return;let n=this.createActivityRailContext(e);if(this.projectActivityRailItems([t],n).some(t=>t.id===e))return{activity:t,context:n}}closeActivityRailItem(e,t){if(this.activeActivityRailId!==e||this.activeActivityRailGeneration!==t)return;let n=this.activityRailRestoreFocus;this.activityRailRestoreFocus=void 0,this.activeActivityRailId=void 0,n!==void 0&&this.updateComplete.then(()=>{this.activeActivityRailId===void 0&&n()})}restoreActivityRailFocus(e){if(e.isConnected){e.focus();return}let t=this.compactActivityRailLauncher;if(t?.isConnected===!0){t.focus();return}this.currentCompactActivityRailLauncher()?.focus()}currentCompactActivityRailLauncher(){let e=this.renderRoot.querySelector(`app-context-bar`)?.shadowRoot?.querySelector(`.activity-rail-action-button`);return e?.isConnected===!0?e:void 0}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Cm(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(Pg(this.state,e))return;let t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?\n\nThis will run git worktree remove and delete:\n${e.path}\n\nThe Git branch will not be deleted.`))return;let n=R(this.state);try{let t=await ms.deleteWorkspace(e.projectId,e.id,n);if(R(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(R(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){R(this.state)===n&&this.setState({error:`Failed to start workspace deletion: ${TF(e)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(R(this.state)!==t)return;let n=Fg(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=R(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{let n=await this.terminalCommandRunsForOrigin(`core`,e).listCommandRuns(jg(t.id));if(R(this.state)!==e)return;let r=Mg(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Ig(t)||await this.handleCompletedWorkspaceDeletionRun(t,e)}catch(e){console.warn(`Failed to refresh workspace deletion runs`,e)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){let e=Object.values(this.state.workspaceDeletionRuns).some(Ig);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=R(this.state)){if(R(this.state)!==t)return;let n=CF(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Fg(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),R(this.state)!==t)return;this.setState({workspaceDeletionRuns:DF(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace deletion failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}openProjectBrowser(e){this.projectBrowserRestoreFocus=e,this.projectBrowserOpen=!0}async showProjectStatistics(e){let t=++this.statisticsRequestGeneration,n=R(this.state),r=()=>t===this.statisticsRequestGeneration&&R(this.state)===n;this.statisticsProject=e,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!0;try{let t=await ms.workspaces(e.id,n);if(!r())return;let i={projectPath:e.path,liveCwds:t.map(e=>e.path)};ps.projectUsageCount(i,n).then(({sessionCount:e})=>{r()&&this.statisticsLoading&&(this.statisticsSessionCount=e)},()=>void 0);let a=await ps.projectUsage(i,n);if(!r())return;this.statisticsReport=a}catch(e){if(!r())return;this.statisticsError=e instanceof Error?e.message:String(e)}finally{r()&&(this.statisticsLoading=!1)}}closeProjectStatistics(){this.statisticsRequestGeneration+=1,this.statisticsProject=void 0,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!1}closeProjectBrowser(e={}){let t=e.restoreFocus===!0?this.projectBrowserRestoreFocus:void 0;this.projectBrowserRestoreFocus=void 0,this.projectBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectProjectFromBrowser(e){this.closeProjectBrowser(),this.selectNavigationItem(`projects`,`workspaces`,()=>this.workspaces.selectProject(e))}addProjectFromBrowser(){this.closeProjectBrowser(),this.openProjectDialog()}openSessionBrowser(e){this.state.selectedProject!==void 0&&(this.sessionBrowserRestoreFocus=e,this.sessionBrowserOpen=!0)}closeSessionBrowser(e={}){let t=e.restoreFocus===!0?this.sessionBrowserRestoreFocus:void 0;this.sessionBrowserRestoreFocus=void 0,this.sessionBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectSessionFromBrowser(e){this.closeSessionBrowser(),this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e))}openProjectDialog(){this.setState({projectDialogOpen:!0})}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebUiStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEBUI gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let e=this.state.selectedMachine;e?.kind!==`remote`||e.baseUrl===void 0||window.open(e.baseUrl,`_blank`,`noopener,noreferrer`)}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id,r=[...e].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);if(!this.sessionModelPolicySupported()){await this.sessions.setModel(n,r);return}let i=await this.prepareActiveModelPolicyDraft();if(i===void 0||i!==this.activeModelPolicyDraftForState(this.state)||i.mode!==`exact`)return;let a=this.selectedMachineModelTierCatalog(),o=a?.models.find(e=>e.model.provider===n&&e.model.id===r);if(o===void 0){a!==void 0&&(this.modelTierCatalogError=`Model ${n}/${r} is unavailable in the model policy catalog`);return}this.modelTierCatalogError=``,this.setActiveModelPolicyDraft(sc(i,o)),this.scheduleActiveExactModelPolicyApply()}openStarterModelDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported(),n=t?this.starterModelPolicy?.exact:void 0,r=n?.model.provider??e.model?.provider,i=n?.model.id??e.model?.id,a=t?(this.selectedMachineModelTierCatalog()?.models??[]).map(e=>({provider:e.model.provider,id:e.model.id,...e.name===void 0?{}:{name:e.name}})):[...e.models],o=r!==void 0&&i!==void 0&&!a.some(e=>e.provider===r&&e.id===i),s=[...o?[...a,{provider:r,id:i}]:a].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Default Model`,source:`starter`,...r!==void 0&&i!==void 0?{selectedValue:`${r}/${i}`}:{},options:s.map(e=>{let t=e.provider??``,n=e.id??``,a=t===r&&n===i;return{value:`${t}/${n}`,label:n+(a?` ✓ current`:``)+(a&&o?` (unavailable)`:``),...t===``?{}:{group:t}}})}})}async pickStarterModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(!(t<=0)){if(this.starterModelPolicySelectionSupported()){let n=this.starterModelPolicy,r=e.slice(0,t),i=e.slice(t+1),a=this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===r&&e.model.id===i);if(n===void 0||a===void 0)return;this.setStarterModelPolicyDraft(sc(n,a));return}await this.updateStarterSessionDefaults({model:{provider:e.slice(0,t),modelId:e.slice(t+1)}})}}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?LP:IP;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${RP}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${RP}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===IP||e===LP){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===IP},this.applyPreferredTheme(!0);return}if(!e.startsWith(RP))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,bg(t),e&&yg(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return xg({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Cg(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?`Follow the system light/dark preference when the selected theme has a pair.`:e.selectedThemePair===void 0?`On, but the selected theme has no light/dark pair, so it will stay selected.`:`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?`light`:`dark`} preference.`}themeOptionLabel(e,t){let n=[...e.id===t?[`selected`]:[],...e.id===this.activeThemeId&&e.id!==t?[`active`]:[]];return n.length===0?e.name:`${e.name} ✓ ${n.join(` · `)}`}themeOptionDescription(e){let t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push(`auto pair`),e.description!==void 0&&t.push(e.description),t.join(` · `)}async openThinkingDialog(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=kF(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){if(this.setState({thinkingDialog:void 0}),e===``)return;if(!this.sessionModelPolicySupported()){await this.sessions.setThinkingLevel(e);return}let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode!==`exact`)return;let n=cc(t,e);if(this.setActiveModelPolicyDraft(n),(this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===n.exact.model.provider&&e.model.id===n.exact.model.id))?.thinkingLevels.includes(e)!==!0){this.cancelActiveModelPolicyApply(),this.modelTierCatalogError=`Thinking level ${e} is unsupported by ${n.exact.model.provider}/${n.exact.model.id}`;return}this.modelTierCatalogError=``,this.scheduleActiveExactModelPolicyApply()}openStarterThinkingDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported()?this.starterModelPolicy?.exact.thinkingLevel??e.thinkingLevel:e.thinkingLevel,n=e.thinkingLevels.includes(t)?e.thinkingLevels:[t,...e.thinkingLevels];this.setState({thinkingDialog:{title:`Select Default Thinking Level`,source:`starter`,selectedValue:t,options:n.map(e=>{let n=kF(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickStarterThinking(e){if(this.setState({thinkingDialog:void 0}),e!==``){if(this.starterModelPolicySelectionSupported()){let t=this.starterModelPolicy;t!==void 0&&this.setStarterModelPolicyDraft(cc(t,e));return}await this.updateStarterSessionDefaults({thinkingLevel:e})}}async updateStarterSessionDefaults(e){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state);try{let r=await hs.updateSessionDefaults(t.path,e,n);if(R(this.state)!==n||this.state.selectedWorkspace?.id!==t.id)return;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let i=this.starterModelPolicy,a=i===void 0?tc(r):nc(i,r);this.starterModelPolicy=a;let o=ec(r);a.mode===`exact`&&o!==void 0&&ic(a.exact,o)&&this.persistStarterModelPolicyPreference(a)}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.publishStarterNotice(Mc(`defaults-failed`,`Could not save this workspace's model defaults. ${TF(e)}`,{machineId:n,workspaceId:t.id}))}}sendPrompt(e,t,n,r){!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,n,r)}async ensureStarterModelPolicyCatalog(){let e=this.selectedMachineModelTierCatalog();return e===void 0?(await this.ensureModelTierCatalog(R(this.state)),this.selectedMachineModelTierCatalog()):e}setStarterModelPolicyDraft(e){this.starterNotice=void 0;let t={mode:e.mode,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel},...e.tier===void 0?{}:{tier:e.tier}};return this.starterModelPolicy=t,t}applyGitUpdateManagerStatus(e,t,n){let r=this.state.selectedWorkspace;R(this.state)!==t||r?.id!==e.id||r.projectId!==e.projectId||this.setState({gitStatus:n,gitStale:!1})}startTerminalModalPointerInteraction(e,t){if(this.terminalModalMaximized||t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.terminal-modal-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=Ky(this.terminalModalBoundsFromFrame(r),this.terminalModalViewport());n.setPointerCapture(t.pointerId),this.terminalModalBounds=i,this.terminalModalPointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}terminalModalBoundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}terminalModalViewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}terminalModalFrameStyle(){let e=this.terminalModalMaximized?void 0:this.terminalModalBounds,t=e===void 0?``:`; left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px`;return`--terminal-modal-opacity: ${String(this.terminalModalOpacity)}%${t};`}finishTerminalModalPointerInteraction(){let e=this.terminalModalPointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.terminalModalPointerInteraction=void 0}}persistTerminalModalPreferences(){eb({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,this.persistWorkspaceTabVisibility()}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,this.persistWorkspaceTabVisibility()}persistWorkspaceTabVisibility(){cb({terminalHidden:this.terminalTabHidden,infoHidden:this.infoTabHidden})}activeModelPolicyInputs(e){let t=e.status?.modelPolicy;if(e.status===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.activeModelPolicyDraftForState(e);if(n===void 0)return{error:e.modelPolicyError??this.modelTierCatalogError,status:t,editorStatus:e.status,thinkingOptions:this.policyThinkingOptions(t.resolved,e.availableThinkingLevels)};let r=n.tier,i=r===void 0||this.selectedMachineModelTierCatalog()?.rows[r].valid!==!0?void 0:this.selectedMachineModelTierCatalog()?.ladder?.[r],a=n.mode===`exact`?n.exact:i??t.resolved,o={mode:n.mode,...r===void 0?{}:{tier:r},resolved:{model:{...a.model},thinkingLevel:a.thinkingLevel},ladderValid:t.ladderValid,...t.blockedReason===void 0?{}:{blockedReason:t.blockedReason}},s=n.exact.model.provider!==``&&n.exact.model.id!==``,c=n.mode===`exact`?{...e.status,...s?{model:{...n.exact.model}}:{},thinkingLevel:n.exact.thinkingLevel,modelPolicy:o}:{...e.status,modelPolicy:o};return{error:e.modelPolicyError??this.modelTierCatalogError,status:o,editorStatus:c,thinkingOptions:this.policyThinkingOptions(n.exact,e.availableThinkingLevels)}}renderChatView(e,t){return g`
|
|
7181
7183
|
<chat-view .sessionId=${t.id} .sessionInfo=${t} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isSendingPrompt=${e.sendingPrompts[t.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[t.id]??[]} .status=${e.status} .warningCount=${this.sessionWarningVisibility.warningCount} .warningsExpanded=${this.sessionWarningVisibility.warningCount>0&&!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .activity=${e.activity} .notificationInbox=${Yp(e.selectedNotificationInbox)} .canClearServerQueue=${this.canClearServerQueue()} .onClearServerQueue=${this.handleClearServerQueue} .canMessageActions=${this.canMessageActions()&&t.archived!==!0} .onEditFromHere=${this.handleEditFromHere} .onForkFromHere=${this.handleForkFromHere} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
|
|
7182
7184
|
`}renderContextBar(){return this.appShell.isDesktopActivityRailLayout?null:g`
|
|
7183
7185
|
<app-context-bar
|
|
@@ -7307,7 +7309,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7307
7309
|
<div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
|
|
7308
7310
|
${e.selectedSession?g`
|
|
7309
7311
|
${this.renderChatView(e,e.selectedSession)}
|
|
7310
|
-
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${R(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${i===void 0?
|
|
7312
|
+
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${R(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${i===void 0?EF(e.status):i.editorStatus} .availableThinkingLevels=${e.availableThinkingLevels} .modelPolicyStatus=${i?.status} .modelTierCatalog=${i===void 0?void 0:this.selectedMachineModelTierCatalog()} .policyThinkingOptions=${i?.thinkingOptions??[]} .modelPolicyLoading=${i!==void 0&&(e.isLoadingModelPolicy||this.modelTierCatalogLoading)} .modelPolicySaving=${i!==void 0&&e.isSavingModelPolicy} .modelPolicyError=${i===void 0?``:i.error} .onSelectPolicyMode=${i===void 0?void 0:this.handleSelectActivePolicyMode} .onSelectPolicyTier=${i===void 0?void 0:this.handleSelectActivePolicyTier} .onSelectPolicyThinking=${i===void 0?void 0:this.handleSelectActivePolicyThinking} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${this.handleSendPrompt} .onStop=${this.handleStopActiveWork} .onSelectModel=${this.handleSelectModel} .onSelectThinking=${this.handleSelectThinking} .onCompact=${t?this.handleCompact:void 0}></prompt-editor>
|
|
7311
7313
|
${e.commandDialog===void 0?null:g`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??``,t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`}
|
|
7312
7314
|
`:this.shouldShowSessionStartScreen(e)?this.renderSessionStartScreen(e):g`<div class="empty">${this.sessionEmptyMessage()}</div>`}
|
|
7313
7315
|
${e.modelDialog===void 0?null:g`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${t=>{e.modelDialog?.source===`starter`?this.pickStarterModel(t):this.pickModel(t)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`}
|
|
@@ -7370,4 +7372,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7370
7372
|
${this.terminalModalOpen?this.renderTerminalModal():null}
|
|
7371
7373
|
${this.settingsSection===void 0?null:g`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .onNavigate=${e=>{this.navigateSettings(e)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${e=>{this.applyClientConfig(e)}} .onModelTiersSaved=${(e,t)=>{this.handleModelTiersSaved(e,t)}} .onRefreshMachineRuntime=${async e=>{await this.machines.refreshMachineRuntime(e)}}></settings-dialog>`}
|
|
7372
7374
|
</div>
|
|
7373
|
-
`}static{this.styles=Zg}};B([S()],$.prototype,`state`,void 0),B([C(`chat-view`)],$.prototype,`chatView`,void 0),B([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),B([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),B([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),B([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),B([S()],$.prototype,`unreadSessionIds`,void 0),B([S()],$.prototype,`activeThemeId`,void 0),B([S()],$.prototype,`isRefreshingApp`,void 0),B([S()],$.prototype,`sessionCleanupDialog`,void 0),B([S()],$.prototype,`historyWindow`,void 0),B([S()],$.prototype,`starterSessionDefaults`,void 0),B([S()],$.prototype,`starterModelPolicyPreferenceReadError`,void 0),B([S()],$.prototype,`starterNotice`,void 0),B([S()],$.prototype,`modelTierCatalog`,void 0),B([S()],$.prototype,`modelTierCatalogLoading`,void 0),B([S()],$.prototype,`modelTierCatalogError`,void 0),B([S()],$.prototype,`starterModelPolicy`,void 0),B([S()],$.prototype,`activeModelPolicyDraft`,void 0),B([S()],$.prototype,`modelsConfigDialogOpen`,void 0),B([S()],$.prototype,`projectBrowserOpen`,void 0),B([S()],$.prototype,`statisticsProject`,void 0),B([S()],$.prototype,`statisticsReport`,void 0),B([S()],$.prototype,`statisticsSessionCount`,void 0),B([S()],$.prototype,`statisticsLoading`,void 0),B([S()],$.prototype,`statisticsError`,void 0),B([S()],$.prototype,`sessionBrowserOpen`,void 0),B([S()],$.prototype,`skillsConfigDialogOpen`,void 0),B([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),B([S()],$.prototype,`systemPromptDialogOpen`,void 0),B([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),B([S()],$.prototype,`terminalModalOpen`,void 0),B([S()],$.prototype,`terminalModalBounds`,void 0),B([S()],$.prototype,`terminalModalMaximized`,void 0),B([S()],$.prototype,`terminalModalFontSize`,void 0),B([S()],$.prototype,`terminalModalOpacity`,void 0),B([S()],$.prototype,`terminalTabHidden`,void 0),B([S()],$.prototype,`infoTabHidden`,void 0),B([S()],$.prototype,`railOrder`,void 0),B([S()],$.prototype,`compactRailOpen`,void 0),B([S()],$.prototype,`activeActivityRailId`,void 0),B([S()],$.prototype,`settingsSection`,void 0),B([S()],$.prototype,`shortcutConfig`,void 0),B([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=B([b(`pi-webui-app`)],$);function
|
|
7375
|
+
`}static{this.styles=Zg}};B([S()],$.prototype,`state`,void 0),B([C(`chat-view`)],$.prototype,`chatView`,void 0),B([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),B([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),B([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),B([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),B([S()],$.prototype,`unreadSessionIds`,void 0),B([S()],$.prototype,`activeThemeId`,void 0),B([S()],$.prototype,`isRefreshingApp`,void 0),B([S()],$.prototype,`sessionCleanupDialog`,void 0),B([S()],$.prototype,`historyWindow`,void 0),B([S()],$.prototype,`starterSessionDefaults`,void 0),B([S()],$.prototype,`starterModelPolicyPreferenceReadError`,void 0),B([S()],$.prototype,`starterNotice`,void 0),B([S()],$.prototype,`modelTierCatalog`,void 0),B([S()],$.prototype,`modelTierCatalogLoading`,void 0),B([S()],$.prototype,`modelTierCatalogError`,void 0),B([S()],$.prototype,`starterModelPolicy`,void 0),B([S()],$.prototype,`activeModelPolicyDraft`,void 0),B([S()],$.prototype,`modelsConfigDialogOpen`,void 0),B([S()],$.prototype,`projectBrowserOpen`,void 0),B([S()],$.prototype,`statisticsProject`,void 0),B([S()],$.prototype,`statisticsReport`,void 0),B([S()],$.prototype,`statisticsSessionCount`,void 0),B([S()],$.prototype,`statisticsLoading`,void 0),B([S()],$.prototype,`statisticsError`,void 0),B([S()],$.prototype,`sessionBrowserOpen`,void 0),B([S()],$.prototype,`skillsConfigDialogOpen`,void 0),B([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),B([S()],$.prototype,`systemPromptDialogOpen`,void 0),B([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),B([S()],$.prototype,`terminalModalOpen`,void 0),B([S()],$.prototype,`terminalModalBounds`,void 0),B([S()],$.prototype,`terminalModalMaximized`,void 0),B([S()],$.prototype,`terminalModalFontSize`,void 0),B([S()],$.prototype,`terminalModalOpacity`,void 0),B([S()],$.prototype,`terminalTabHidden`,void 0),B([S()],$.prototype,`infoTabHidden`,void 0),B([S()],$.prototype,`railOrder`,void 0),B([S()],$.prototype,`compactRailOpen`,void 0),B([S()],$.prototype,`activeActivityRailId`,void 0),B([S()],$.prototype,`settingsSection`,void 0),B([S()],$.prototype,`shortcutConfig`,void 0),B([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=B([b(`pi-webui-app`)],$);function $P(){let e=new bv;return e.register({id:`core`,plugin:Y_}),e.register({id:`themes`,plugin:ev}),e}function eF(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:`local`,kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function tF(e,t){return JSON.stringify([e,t.id,t.cwd])}function nF(e){let t=e.selectedSession;return t===void 0?void 0:tF(R(e),t)}function rF(e){let t=e.selectedSession;return t===void 0?void 0:JSON.stringify([R(e),t.id,t.cwd])}function iF(e){return JSON.stringify([R(e),e.selectedWorkspace?.id,e.selectedWorkspace?.path,e.selectedSession?.id,e.selectedSession?.cwd])}function aF(e){if(oF(e)!==void 0&&sF(e,R(e)))return rF(e)}function oF(e){return e.status?.modelPolicy}function sF(e,t){if(t===`local`)return!0;let n=e.machineRuntimes[t];return n?.ok===!0&&E(n,w.sessionsModelPolicy)}function cF(e,t){let n=e.machineRuntimes[t];return n?.ok===!0&&E(n,w.sessionsModelPolicyStarterSelection)}function lF(e){return e!==void 0&&`starterModelPolicyContractVersion`in e}function uF(e,t){return e.mode===t.mode&&e.tier===t.tier&&ic(e.exact,t.exact)}function dF(e){return e.id===WP||e.sourcePluginId===HP&&e.localId===UP}function fF(e){return e.id===qP||e.sourcePluginId===GP&&e.localId===KP}function pF(e,t){return R(e)!==R(t)||e.selectedProject?.id!==t.selectedProject?.id||e.selectedWorkspace?.id!==t.selectedWorkspace?.id||e.selectedWorkspace?.path!==t.selectedWorkspace?.path}function mF(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function hF(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function gF(e,t){return _F(e,t)}function _F(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function vF(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function yF(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function bF(e){return Wc(e.status,e.activity)}function xF(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function SF(){return{}}function CF(e,t){return JSON.stringify([e,t])}function wF(e){return PP[Math.min(e,PP.length-1)]??3e4}function TF(e){return e instanceof Error?e.message:String(e)}function EF(e){if(e?.modelPolicy===void 0)return e;let t={...e};return delete t.modelPolicy,t}function DF(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function OF(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function kF(e){switch(e){case`off`:return`No reasoning`;case`minimal`:return`Very brief reasoning (~1k tokens)`;case`low`:return`Light reasoning (~2k tokens)`;case`medium`:return`Moderate reasoning (~8k tokens)`;case`high`:return`Deep reasoning (~16k tokens)`;case`xhigh`:return`Maximum reasoning (~32k tokens)`;default:return}}export{y as a,b as i,C as n,g as o,x as r,h as s,B as t};
|